【发布时间】:2019-12-20 04:02:40
【问题描述】:
与任何地方一样,这段代码应该用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
【问题讨论】:
-
您打开它一次并无限写入。仅当您关闭并重新打开文件时,您的文件才会被覆盖。
标签: python multithreading file io