io.UnsupportedOperation: not writable, can't write to .py files

1.1k views Asked by At

Using this code:

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

I get the following error and I don't know how to fix it.

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

There are 1 answers

0
inteoryx On

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".