我正在尝试学习 python 并想将一些文本写入文件。我遇到了两种文件对象。
fout=open("abc.txt",a)
以 open("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
关于Python-将文本写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35120899/