简体   繁体   English

函数不写入文本文件

[英]function not writing to text file

I'm trying to make a sort of logbook in a text file to avoid re-doing efforts.我试图在文本文件中制作一种日志,以避免重新做工作。 I have the following function that perform this task:我有以下执行此任务的功能:

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

When I check the text file after I run the script, it remains empty.当我在运行脚本后检查文本文件时,它仍然是空的。 I'm not sure why.我不知道为什么。

I call it as such (in reality target name is pulled down from a unique ID, but since I don't want to put everything here, this is the gist):我这样称呼它(实际上目标名称是从一个唯一的 ID 中拉下来的,但由于我不想把所有东西都放在这里,这是要点):

target_name = 'abc123'
write_to_logbook(target_name)

You need to (potentially) read the entire file before you can decide if target_name has to be added to the file.您需要(可能)阅读整个文件,然后才能决定是否必须将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 will return True as soon as any line containing target_name is found, at which point the function itself will return.一旦找到任何包含target_name行, any将返回True ,此时函数本身将返回。

If the target name isn't found after reading the entire file, then the second with statement will append the target name to the file.如果在读取整个文件后未找到目标名称,则第二个with语句会将目标名称附加到文件中。

I got it sorted.我整理好了I used chepner's solution as a jumping off point, since it didn't exactly work (only wrote one target_name for some reason) and kind of did a hybrid of the two:我使用 chepner 的解决方案作为起点,因为它并不完全有效(出于某种原因只写了一个target_name )并且有点混合了两者:

def 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')

Thanks for the solution, it helped.感谢您的解决方案,它有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM