1

使用此代码:

data = open("data.py")
for i, line in enumerate(data):
    if i == 7:
        data.write("test")

我收到以下错误,我不知道如何解决它。

Traceback (most recent call last):
  File "H:\py\Projects\osuGatcha\main.py", line 61, in <module>
    data.write("test")
io.UnsupportedOperation: not writable
4

1 回答 1

0

By default "open" returns a file object that is readable, but not writable. In other words, you can read the file you opened but you cannot write to it. To write to the file include a second argument indicating you want to write to the file.

data = open("data.py", "w")

See more in section 7.2 here. Also, be careful! Opening a file to write to it will overwrite the contents of the file that currently exist. If you just want to add to the end of an existing file you would open it in "append" mode, or with an "a" instead of a "w".

于 2021-10-26T18:45:54.813 回答