I made a simple program but It shows the following error when I run it:
line1 = []
line1.append("xyz ")
line1.append("abc")
line1.append("mno")
file = open("File.txt","w")
for i in range(3):
file.write(line1[i])
file.write("\n")
for line in file:
print(line)
file.close()
It shows this error message:
File "C:/Users/Sachin Patil/fourth,py.py", line 18, in
for line in file:
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.
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
If you want to open a file for both reading, writing and create it if it doesn't exist then I suggest you use a+
.
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 block's end, even if an exception is raised on the way. It's equivalent to try-finally
, but much shorter.