虽然在python中以“ w”模式打开但文件未覆盖?

时间:2019-08-13 14:56:36

标签: python multithreading file io

就像在任何地方一样,这段代码应该使用last_index变量中的值覆盖文件上的内容,因为文件是在w模式下打开的。

from threading import *

def function():
    with open('important.cache', 'w') as f:
        while True:
            f.write(str(last_index))

mythread = Thread(target=function)
mythread.start()

但是我的important.cache文件看起来像这样,

0000000000000000000000000000000000000011111111111111111111111111122222222222222222222222222222222222222333333333333333333333333333333333333333333333333333333333334444444444444444444444444444444555555555555555555

我希望它看起来像

0

这应该在循环的每个循环中被覆盖。 这样吧

1

2

the value of the variable last_index at that time

1 个答案:

答案 0 :(得分:1)

您也许应该切换循环的顺序。就像您说的那样,'w'模式确实会删除文件的内容,但这是在您调用open函数时而不是在您调用write时做到的。

from threading import *

def function():
    while True:
        with open('important.cache', 'w') as f:
            f.write(str(last_index))

mythread = Thread(target=function)
mythread.start()

您会看到有时important.cache文件为空。这是因为while循环非常快,并且擦除和写入文件的速度非常快。为了解决这个问题,您应该在write语句(time.sleep(0.01))可能可行之后调用一次小睡眠。