我注意到在使用Python写入文件时,内容会在关闭后写入文件。
例如:
with open('test.txt','w') as ffile:
ffile.write("testing")
time.sleep(20)
在此示例中" 测试"将在等待20秒后写完。
这是如何以及为何发生的?为什么不同时写文件?
答案 0 :(得分:4)
您正在看到缓冲的效果。磁盘I / O使用缓冲区来提高性能,并且您没有将足够的数据写入缓冲区以使其刷新。
写入更多数据或关闭文件都会导致刷新缓冲区。或者,将缓冲区大小设置为一个非常小的数字(缓冲区将保存的字节数):
with open('test.txt', 'w', 2) as ffile:
选项0
和1
具有特殊含义; 0
将完全禁用缓冲(仅适用于二进制模式文件),1
是文本文件的默认值(使用 line buffering ,写一个新线冲洗)。
这也意味着如果你有一个文本文件,你可以写一个换行符来触发flush:
ffile.write('\n')
最后但并非最不重要的是,您可以使用file.flush()
method:
ffile.flush()
答案 1 :(得分:1)
with open('test.txt','w') as ffile:
ffile.write("testing")
ffile.flush() # This forces the buffer to be written to the file.
time.sleep(20)