我试图将一个字符串附加到文件,如果该字符串没有在文件中退出.但是,打开带有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'?
您可以使用设置文件对象的当前位置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)