我有一个打开的文件,我想搜索直到在一行的开头找到特定的文本短语。然后我想用“句子”覆盖那一行
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 许可协议
您可以打开一个文件进行同时读写,但它不会按您期望的方式工作:
您可以覆盖字节或扩展文件,但如果不重写当前位置之后的所有内容,则无法插入或删除字节。由于线条的长度不尽相同,因此最简单的方法是分两个步骤进行: