Recently, I was trying to write into a text file in Python to open it later, but my terminal dropped the message “not writable”.
I guess it may be an UnsupportedOperation problem, but I couldn’t read anyathing in my terminal like that, it just said “not writable.
What could be the problem? Thanks in advance.
with open('test.txt') as test:
test.write("""Here I pasted what I wanted to write""")
with open('test.txt') as test:
question = test.read()
print(question)
And what the terminal said:
File “C:DesktopPythonmain.py” in line 2: not writable
That’s all I’ve tried so far.
Dave Summer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3
You’re trying to write to the file without opening it in write mode. By default, when you open
a file with open('filename')
, it opens in read mode. Since read mode doesn’t allow writing, attempting to call test.write()
results in the “not writable” error.
To fix this, you need to open the file in write ('w'
), append ('a'
), or read/write ('r+'
) mode, depending on your needs. For example:
with open('test.txt', 'w') as test:
test.write('Here I pasted what I wanted to write')
with open('test.txt', 'r') as test:
question = test.read()
print(question)
Output:
Here I pasted what I wanted to write
Try on godbolt.org
the default opening mode for open
is read only (you can find this out easily by reading the docs). So just open the file for writing when you want to write, and for reading when you want to read it:
with open('test.txt', 'w') as test:
# Open the file for writing by specifying "w"
test.write("""Here I pasted what I wanted to write""")
with open('test.txt', 'r') as test:
# Open the file for reading text by default so no change needed
question = test.read()
print(question)