gpt4 book ai didi

python - 值错误 : must have exactly one of create/read/write/append mode

转载 作者:太空宇宙 更新时间:2023-11-03 13:57:14 27 4
gpt4 key购买 nike

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

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

我怎样才能让它工作?

最佳答案

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

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))

关于python - 值错误 : must have exactly one of create/read/write/append mode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53917479/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com