【问题标题】:File not overwritten though opened in 'w' mode in python?尽管在 python 中以“w”模式打开,但文件没有被覆盖?
【发布时间】: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


【解决方案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)) 可能会起作用之后调用一个小睡眠。

【讨论】:

  • 你能解释一下答案吗
  • 是的!现在检查。我修改了我的答案。如果它对您有用,请不要忘记接受我的回答:D
  • 或者甚至考虑你希望循环在什么情况下停止并在写入后有你的中断情况。
猜你喜欢
  • 2023-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-10
  • 2021-12-31
  • 2013-06-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多