Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中打开或创建文件并附加到它_Python_File_Append - Fatal编程技术网

在python中打开或创建文件并附加到它

在python中打开或创建文件并附加到它,python,file,append,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:

如何在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()

如果在最初打开文件后尚未将其关闭,则无需重新打开该文件。打开文件时使用“a”以附加到文件中。所以“else:打开(路径,“a”)作为f:f.write(字符串)”。尝试一下

如果在最初打开文件后还没有关闭它,则无需重新打开该文件。打开文件时使用“a”以附加到文件中。所以“else:打开(路径,“a”)作为f:f.write(字符串)”。试试这个

试试这个:

with open(path, 'a+') as file:
    file.seek(0)
    content = file.read()
    if string not in content:
        file.write(string)
seek会将指针移到起点,write会将指针移回终点

编辑: 此外,您不需要检查路径。 例如:

文件示例不存在,但当我调用open()时,它被创建了

试试这个:

with open(path, 'a+') as file:
    file.seek(0)
    content = file.read()
    if string not in content:
        file.write(string)
seek会将指针移到起点,write会将指针移回终点

编辑: 此外,您不需要检查路径。 例如:


文件示例不存在,但当我调用open()时,它被创建了

我也尝试了你的版本,但是我认为我在os.path.exists上有问题,因为总是使用不存在的brancha+和w+在编写新文件时会自动创建新文件,所以你不需要检查路径是否存在。我提供的代码已经完成。我刚刚用新信息编辑了我的答案。我也尝试了你的版本,但我想我在os.path.exists上有问题,因为始终使用不存在brancha+和w+会在编写新文件时自动创建新文件,所以你不需要检查路径是否存在。我提供的代码已经完成。我刚刚用新信息编辑了我的答案。