我有一个关于Python在文件中打开和写入数据时的行为的问题。
我有一个大的代码,是建立运行甚至数小时,它涉及到写ASCII文件的文本。代码使用with open
方法,并在程序运行期间保持文件打开。
有时我需要停止程序的执行,从而获得Process finished with exit code -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"
在第一种情况下,文本写在文件中,但是在第二种情况下,我得到的是空的。 为什么会发生这种情况?我该如何解决?你知道吗
首先,您可能需要确保确实在向磁盘而不是缓冲区写入数据。你知道吗
一种方法是使用
infile2.flush()
:另一种方法是open the file with no buffering。在
open
调用中,设置buffering=0
。你知道吗前一种方法让你有责任记得冲水。另一方面,它使您能够更好地控制何时刷新“检查点”。通常,自动无缓冲IO的吞吐量较低。你知道吗
相关问题 更多 >
编程相关推荐