ValueError:必须正好有一个create/read/write/append mod

2024-04-20 10:20:18 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我怎样才能让这工作?


Tags: thetopathtextobjectusemainas
3条回答

不能对同一文件进行读写操作。你必须从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)

开启方式如下:

  • “r”打开文本文件进行读取。流位于 文件的开头。

  • “r+”打开进行读写。溪流被定位 在 文件的开头。

  • “w”将文件截断为零长度或创建 写作。 流位于文件的开头。

  • “w+”打开进行读写。如果文件是 没有 存在,否则将被截断。溪流位于 文件的开头。

  • “a”打开进行写入。如果文件没有 存在。这个 流位于文件的末尾。后续写入 到文件的结尾总是在文件的当前结尾, 不考虑任何介入的fseek(3)或类似情况。

  • “a+”打开进行读写。如果文件是 没有 存在。流位于文件的末尾。子集- 昆特对文件的写入总是以当前的结尾 文件结束,不考虑任何介入的fseek(3)或类似内容。

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

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

相关问题 更多 >