[英]Python- Writing text to a file?
我正在尝试学习python,并希望将一些文本写入文件。 我遇到了两种文件对象。
FOUT =打开( “的abc.txt”,一)
打开(“abc.txt”,a)作为fout:
以下代码:
f= open("abc.txt", 'a')
f.write("Step 1\n")
print "Step 1"
with open("abc.txt", 'a') as fout:
fout.write("Step 2\n")
给出了输出:
Step 2
Step 1
以下代码:
f= open("abc1.txt", 'a')
f.write("Step 1\n")
f= open("abc1.txt", 'a')
f.write("Step 2\n")
给出了输出:
Step 1
Step 2
为什么输出有差异?
只有一种类型的文件对象,只有两种不同的方法来创建一个。 主要区别在于with open("abc.txt",a) as fout:
行处理为您关闭文件,因此它不易出错。
发生的事情是您使用fout=open("abc.txt",a)
语句创建的文件在程序结束时自动关闭,因此只会发生追加。
如果您运行以下代码,您将看到它以正确的顺序生成输出:
f = open("abc.txt", 'a')
f.write("Step 1\n")
f.close()
with open("abc.txt", 'a') as fout:
fout.write("Step 2\n")
线条反转的原因是文件被关闭的顺序。 您的第一个示例中的代码与此类似:
f1 = open("abc.txt", 'a')
f1.write("Step 1\n")
# these three lines are roughly equivalent to the with statement (providing no errors happen)
f2 = open("abc.txt", 'a')
f2.write("Step 2\n")
f2.close() # "Step 2" is appended to the file here
# This happens automatically when your program exits if you don't do it yourself.
f1.close() # "Step 1" is appended to the file here
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.