jam*_*mes 1 python file append
你如何在Python中执行这一系列操作?
1)如果文件不存在则创建一个文件并插入字符串
2)如果文件存在,则查找是否包含字符串
3)如果字符串不存在,则挂在文件末尾
我目前正在这样做,但我错过了一步
每次我调用该函数时都使用此代码进行编辑似乎该文件不存在并覆盖旧文件
def func():
if not os.path.exists(path):
    #always take this branch
    with open(path, "w") as myfile:
        myfile.write(string)
        myfile.flush()
        myfile.close()
else:
    with open(path) as f:
        if string in f.read():
            print("string found")
        else:
            with open(path, "a") as f1:
                f1.write(string)
                f1.flush()
                f1.close()
    f.close()
尝试这个:
with open(path, 'a+') as file:
    file.seek(0)
    content = file.read()
    if string not in content:
        file.write(string)
search 会将指针移至开头,而 write 会将指针移回结尾。
编辑:另外,您不需要检查路径。例子:
>>> f = open('example', 'a+')
>>> f.write('a')
1
>>> f.seek(0)
0
>>> f.read()
'a'
文件示例不存在,但是当我调用 open() 时它被创建了。看看为什么
| 归档时间: | 
 | 
| 查看次数: | 5862 次 | 
| 最近记录: |