ValueError:必须恰好具有创建/读取/写入/附加模式之一

新手上路,请多包涵

我有一个打开的文件,我想搜索直到在一行的开头找到特定的文本短语。然后我想用“句子”覆盖那一行

sentence = "new text"           "
with open(main_path,'rw') as file: # Use file to refer to the file object
    for line in file.readlines():
        if line.startswith('text to replace'):
            file.write(sentence)

我越来越:

 Traceback (most recent call last):
 File "setup_main.py", line 37, in <module>
with open(main_path,'rw') as file: # Use file to refer to the file object
ValueError: must have exactly one of create/read/write/append mode

我怎样才能让这个工作?

原文由 user1592380 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 786
2 个回答

您可以打开一个文件进行同时读写,但它不会按您期望的方式工作:

 with open('file.txt', 'w') as f:
    f.write('abcd')

with open('file.txt', 'r+') as f:  # The mode is r+ instead of r
    print(f.read())  # prints "abcd"

    f.seek(0)        # Go back to the beginning of the file
    f.write('xyz')

    f.seek(0)
    print(f.read())  # prints "xyzd", not "xyzabcd"!

您可以覆盖字节或扩展文件,但如果不重写当前位置之后的所有内容,则无法插入或删除字节。由于线条的长度不尽相同,因此最简单的方法是分两个步骤进行:

 lines = []

# Parse the file into lines
with open('file.txt', 'r') as f:
    for line in f:
        if line.startswith('text to replace'):
            line = 'new text\n'

        lines.append(line)

# Write them back to the file
with open('file.txt', 'w') as f:
    f.writelines(lines)

    # Or: f.write(''.join(lines))

原文由 Blender 发布,翻译遵循 CC BY-SA 4.0 许可协议

您不能读取和写入同一个文件。您必须从 main_path 读取,然后写入另一个,例如

sentence = "new text"
with open(main_path,'rt') as file: # Use file to refer to the file object
    with open('out.txt','wt') as outfile:
        for line in file.readlines():
            if line.startswith('text to replace'):
                outfile.write(sentence)
            else:
                outfile.write(line)

原文由 zyxue 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏