【发布时间】:2021-01-11 19:45:27
【问题描述】:
代码每 30 秒生成一个带有日期/时间的文件,然后将 self.log 中的“密钥”键入其中。问题是当新文件被生成并且'key'被输入时,它只是将自己附加到底部并且不会覆盖新生成文件中的旧内容。 非常感谢您的帮助:)
def report(self):
if self.log:
print(self.log)
starttime = time.time()
while True:
timestr = time.strftime("%Y%m%d-%H%M%S")
fileloc = f'C:/logging/pylogger/{timestr}.txt'
with open(fileloc, mode='w') as f:
f.seek(0)
f.truncate()
for key in self.log:
f.write(key)
time.sleep(30.0 - ((time.time() - starttime) % 30.0))
【问题讨论】:
-
mode='w'覆盖内容。无需seek和truncate。