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

时间:2015-02-07 17:44:44

标签: python

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

在代码中,显然,下面没有工作。

file = open("fileName", "a+")

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

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()

2 个答案:

答案 0 :(得分:21)

如果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

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

在循环Python语法之后,代码使用了模糊的else。见Why does python use 'else' after for and while loops?

答案 1 :(得分:7)

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

f.seek(0, os.SEEK_SET)

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

f.seek(0, os.SEEK_END)

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

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")
相关问题