首页 > 解决方案 > 函数不写入文本文件

问题描述

我正在尝试在文本文件中制作一种日志以避免重复工作。我有以下执行此任务的功能:

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)

标签: pythontext

解决方案


您需要(可能)阅读整个文件,然后才能决定是否target_name必须将其添加到文件中。

def 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将在找到True任何包含target_name的行后立即返回,此时函数本身将返回。

如果读取整个文件后没有找到目标名称,则第二with条语句会将目标名称附加到文件中。


推荐阅读