Python:打开一个文件,搜索然后追加,如果不存在的话

Yui*_*ark 14 python

我试图将一个字符串附加到文件,如果该字符串没有在文件中退出.但是,打开带有a+选项的文件不允许我立即执行,因为打开文件a+会将指针放到文件的末尾,这意味着我的搜索将始终失败.有没有什么好的方法可以做到这一点,除了打开文件先读取,关闭再打开附加?

在代码中,显然,下面不起作用.

file = open("fileName", "a+")
Run Code Online (Sandbox Code Playgroud)

我需要做以下才能实现它.

file = open("fileName", "r")
... check if a string exist in the file
file.close()

... if the string doesn't exist in the file
file = open("fileName", "a")
file.write("a string")
file.close()
Run Code Online (Sandbox Code Playgroud)

jfs*_*jfs 24

如果输入文件needle在任何行上,则保持输入文件不变;如果缺少,则将针附加到文件的末尾:

with open("filename", "r+") as file:
    for line in file:
        if needle in line:
           break
    else: # not found, we are at the eof
        file.write(needle) # append missing data
Run Code Online (Sandbox Code Playgroud)

我已经测试了它,它适用于Python 2(基于stdio的I/O)和Python 3(基于POSIX读/写的I/O).

代码else在循环Python语法之后使用模糊.看看为什么python在for循环和while循环之后使用'else'?

  • @glglgl:也许一个downvoter不熟悉"循环后的'else`"语法,他们认为我错误地使用了缩进. (3认同)
  • 好东西。仅供参考,因为这对我来说是新的;else 语句与 for/while 循环结合使用称为“完成子句”的概念。 (2认同)

Car*_*ten 7

您可以使用设置文件对象的当前位置file.seek().要跳转到文件的开头,请使用

f.seek(0, os.SEEK_SET)
Run Code Online (Sandbox Code Playgroud)

要跳转到文件的末尾,请使用

f.seek(0, os.SEEK_END)
Run Code Online (Sandbox Code Playgroud)

在你的情况下,要检查文件是否包含某些内容,然后可能追加到该文件,我会做这样的事情:

import os

with open("file.txt", "r+") as f:
    line_found = any("foo" in line for line in f)
    if not line_found:
        f.seek(0, os.SEEK_END)
        f.write("yay, a new line!\n")
Run Code Online (Sandbox Code Playgroud)