我有一个打开的文件,我想搜索,直到在一行的开头找到特定的文本短语。然后我想用“句子”覆盖那一行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 objectValueError: must have exactly one of create/read/write/append mode我怎样才能让它工作?
3 回答
幕布斯6054654
TA贡献1876条经验 获得超7个赞
您无法读取和写入同一个文件。你必须从 读取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)
哆啦的时光机
TA贡献1779条经验 获得超6个赞
不是示例代码的问题,而是想分享,因为这是我在搜索错误时结束的地方。
由于在 Windows 上附加到文件时选择的文件名(例如 con.txt),我收到此错误。将扩展名更改为其他可能性会导致相同的错误,但更改文件名解决了问题。结果是文件名选择导致重定向到控制台
添加回答
举报
0/150
提交
取消