函数不写入文本文件

我试图在文本文件中制作一种日志,以避免重复工作。我有以下函数来执行此任务:


def write_to_logbook(target_name):


   with open('C:\Documents\logbook.txt', 'a+') as f:

      for lines in f:

          if target_name not in lines:

              f.write(target_name + '\n')

              f.close() #when I didn't have f.close() here, it also wasn't writing to the txt file

当我在运行脚本后检查文本文件时,它保持为空。我不知道为什么。


我这样称呼它(实际上目标名称是从唯一ID中提取的,但由于我不想把所有东西都放在这里,所以这是要点):


target_name = 'abc123'

write_to_logbook(target_name)


繁华开满天机
浏览 88回答 2
2回答

呼如林

您需要(可能)读取整个文件,然后才能决定是否必须将其添加到文件中。target_namedef write_to_logbook(target_name):    fname = r'C:\Documents\logbook.txt')    with open(fname) as f:        if any(target_name in line for line in f):            return    with open(fname, 'a') as f:        print(target_name, file=f)any一旦找到包含的任何行,就会返回,此时函数本身将返回。Truetarget_name如果在读取整个文件后找不到目标名称,则第二个语句会将目标名称附加到文件中。with

Helenr

我把它整理好了。我使用chepner的解决方案作为起点,因为它并不完全有效(出于某种原因只写了一个),并且有点混合了两者:target_namedef write_to_logbook(target_name):    fname = 'filepath'    with open(fname) as f:        for lines in f:            if target_name in lines:                return    with open(fname, 'a+') as f:        f.write(target_name + '\n')感谢您的解决方案,它有所帮助。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python