就像在任何地方一样,这段代码应该使用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
答案 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)
)可能可行之后调用一次小睡眠。