我对 Python 在文件中打开和写入数据时的行为有疑问。
我有一个大型代码,甚至可以运行几个小时,它涉及在 ASCII 文件中写入文本。该代码使用 with open
方法并在程序运行期间保持文件打开。
有时我需要停止程序的执行,从而获得进程已完成,退出代码为-1
退出状态。
困扰我的问题是,当代码运行时,我得到了文本已写入 ASCII 文件的确认,但如果我停止代码,文件就是空的,这种奇怪的行为。 我们以下面的代码为例:
import time
# Create the .txt files
with open('D:/Stuff/test1.txt', 'w') as write1:
pass
with open('D:/Stuff/test2.txt', 'w') as write2:
pass
# Write some text into the.txt files
# Case 1. The code runs until the end
with open ('D:/Stuff/test1.txt', 'a') as infile1:
a = range(1, 50, 1)
infile1.write(str(a))
print "Writing completed!"
# Case 2. I stop the execution manually. I use time.sleep to be able to stop it in this example
with open ('D:/Stuff/test2.txt', 'a') as infile2:
b = range(1, 50, 1)
infile2.write(str(b))
print "Writing completed!"
print "Start sleep"
time.sleep(10)
<< At this line I end the script manually>>
print "End sleep"
发生的情况是,在情况 1 中,文本写入文件中,但在情况 2 中,我将它们清空。 为什么会发生这种情况以及如何解决?
最佳答案
首先,您可能需要确保确实正在写入磁盘,而不是缓冲区。
一种方法是使用infile2.flush()
:
infile2.write(str(b))
infile2.flush() # <- here
print "Writing completed!"
另一种方法是open the file with no buffering 。在 open
调用中,设置 buffering=0
。
前一种方法让您有责任记住冲水。另一方面,它可以让您更好地控制何时刷新“检查点”。一般来说,自动无缓冲 IO 的吞吐量较低。
关于python - 写入文件时的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38849913/