【问题标题】:open or create file in python and append to it在 python 中打开或创建文件并附加到它
【发布时间】:2020-03-05 08:11:21
【问题描述】:

这一系列的动作在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()

【问题讨论】:

    标签: python file append


    【解决方案1】:

    试试这个:

    with open(path, 'a+') as file:
        file.seek(0)
        content = file.read()
        if string not in content:
            file.write(string)
    

    seek 会将您的指针移至开头,而 write 会将其移回末尾。

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

    >>> f = open('example', 'a+')
    >>> f.write('a')
    1
    >>> f.seek(0)
    0
    >>> f.read()
    'a'
    

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

    【讨论】:

    • 我也试过你的版本,但我认为 os.path.exists 有问题,因为总是采用不存在的分支
    • a+和w+在写新文件的时候会自动创建新文件,所以不需要检查路径是否存在tutorialspoint.com/python/python_files_io.htm
    • 我提供的代码已经完成。我刚刚用新信息编辑了我的答案。
    【解决方案2】:

    如果您在最初打开文件后尚未将其关闭,则无需重新打开该文件。打开文件时使用“a”以附加到它。所以...“else: with open(path, "a") as f: f.write(string)".试试看

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-26
      • 2020-10-15
      • 2021-09-23
      • 1970-01-01
      • 1970-01-01
      • 2017-09-28
      • 2021-11-29
      相关资源
      最近更新 更多