覆盖新生成文件的内容
Posted
技术标签:
【中文标题】覆盖新生成文件的内容【英文标题】:Overwrite content of new generated file 【发布时间】: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
。
【参考方案1】:
您的问题对我来说并不完全清楚,但如果我正确理解,您需要在编写后从列表中删除元素:
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)
self.log.remove(key)
time.sleep(30.0 - ((time.time() - starttime) % 30.0))
只需在您的 for 循环中添加 self.log.remove(key)
,这样一旦写入,值就会从列表中删除,当您在 30 秒后到达下一个循环时,新文件将仅包含新值。
【讨论】:
以上是关于覆盖新生成文件的内容的主要内容,如果未能解决你的问题,请参考以下文章