写文件时的奇怪行为

2024-04-24 17:27:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个关于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"

在第一种情况下,文本写在文件中,但是在第二种情况下,我得到的是空的。 为什么会发生这种情况?我该如何解决?你知道吗


Tags: 文件the代码文本txttimeaswith
1条回答
网友
1楼 · 发布于 2024-04-24 17:27:08

首先,您可能需要确保确实在向磁盘而不是缓冲区写入数据。你知道吗

一种方法是使用infile2.flush()

infile2.write(str(b))
infile2.flush() # <- here
print "Writing completed!"

另一种方法是open the file with no buffering。在open调用中,设置buffering=0。你知道吗

前一种方法让你有责任记得冲水。另一方面,它使您能够更好地控制何时刷新“检查点”。通常,自动无缓冲IO的吞吐量较低。你知道吗

相关问题 更多 >