python - 覆盖新生成文件的内容
问题描述
该代码每 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))
解决方案
您的问题对我来说并不完全清楚,但如果我正确理解,您需要在编写后从列表中删除元素:
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))
只需添加self.log.remove(key)
你的 for 循环,这样一旦写入,值就会从列表中删除,当你在 30 秒后到达下一个循环时,新文件将只包含新值。
推荐阅读
- javascript - Vue 循环获取 api 数组对象并在 Spa 中显示上一个/下一个按钮和默认的第一个视图
- c# - WPF / C#: Translating Text in Datagrid Based on Control Parameter
- android - 如何将视图设置为可访问性按钮之类的控制器
- function - 如何在没有痛苦的类型转换的情况下评估 GDB 中的函数?
- python - Python: Monthly Sales - cannot get the commands to read from file
- java - Java Optional.ifPresentOrElse 带返回值
- neo4j - 如何在 Neo4J 中安装“图形算法”扩展?
- bash - BASH How to use each line of a file as a variable input within for loop
- java - 缺少 Servlet 内容
- linux - Slack App Bot 无法向频道发布消息