往文件里面写内容,写完了,内容就自动保存了。
使用with open()语句是python最常用的打开文件方式,会在文件对象使用完毕后,自动关闭,无需手动书写close ()。
要保存数据至文件,代码可参照这样写:
boys=['John','Tommy','Bob']
girls=['Anna','Barbara','Cathy']
with open('boys.txt','w',encoding='utf-8') as f1,open('girls.txt','w',encoding='utf-8') as f2:
f1.writelines('\n'.join(boys))
f2.writelines('\n'.join(girls))
如有帮助,请采纳。点击我回答右上角【采纳】按钮。
写文件分为三步:
1、fw = open(file,"w")
2、fw.write(content)
3、fw.close()
内容content就会被写入到文件file中。