首页 > 解决方案 > 覆盖新生成文件的内容

问题描述

该代码每 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))

标签: pythonfileoverwrite

解决方案


您的问题对我来说并不完全清楚,但如果我正确理解,您需要在编写后从列表中删除元素:

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 秒后到达下一个循环时,新文件将只包含新值。


推荐阅读