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

我怎样才能让它工作?


FFIVE
浏览 542回答 3
3回答

幕布斯6054654

您无法读取和写入同一个文件。你必须从 读取main_path,然后写入另一个,例如sentence = "new text"with open(main_path,'rt') as file: # Use file to refer to the file object&nbsp; &nbsp; with open('out.txt','wt') as outfile:&nbsp; &nbsp; &nbsp; &nbsp; for line in file.readlines():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if line.startswith('text to replace'):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; outfile.write(sentence)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; outfile.write(line)

哆啦的时光机

不是示例代码的问题,而是想分享,因为这是我在搜索错误时结束的地方。由于在 Windows 上附加到文件时选择的文件名(例如 con.txt),我收到此错误。将扩展名更改为其他可能性会导致相同的错误,但更改文件名解决了问题。结果是文件名选择导致重定向到控制台
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python