file – Python error message io.UnsupportedOperation: not readable

file – Python error message io.UnsupportedOperation: not readable

You are opening the file as w, which stands for writable.

Using w you wont be able to read the file. Use the following instead:

file = open(File.txt,r)

Additionally, here are the other options:

r   Opens a file for reading only.
r+  Opens a file for both reading and writing.
rb  Opens a file for reading only in binary format.
rb+ Opens a file for both reading and writing in binary format.
w   Opens a file for writing only.
a   Open for writing.  The file is created if it does not exist.
a+  Open for reading and writing.  The file is created if it does not exist.

Use a+ to open a file for reading, writing and create it if it doesnt exist.

a+ Opens a file for both appending and reading. The file pointer is at
the end of the file if the file exists. The file opens in the append
mode. If the file does not exist, it creates a new file for reading
and writing. –Python file modes

with open(File.txt, a+) as file:
    print(file.readlines())
    file.write(test)

Note: opening file in a with block makes sure that the file is properly closed at the blocks end, even if an exception is raised on the way. Its equivalent to try-finally, but much shorter.

file – Python error message io.UnsupportedOperation: not readable

There are few modes to open file (read, write etc..)

If you want to read from file you should type file = open(File.txt,r), if write than file = open(File.txt,w). You need to give the right permission regarding your usage.

more modes:

  • r. Opens a file for reading only.
  • rb. Opens a file for reading only in binary format.
  • r+ Opens a file for both reading and writing.
  • rb+ Opens a file for both reading and writing in binary format.
  • w. Opens a file for writing only.
  • you can find more modes in here

Leave a Reply

Your email address will not be published.