Python error message io.UnsupportedOperation: not readable

Viewed 199559

I have this code:

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()

But when I try it, I get an error message like:

  File "...", line 18, in <module>
     for line in file:
 
UnsupportedOperation: not readable

Why? How do I fix it?

5 Answers

Use a+ to open a file for reading, writing and create it if it doesn't 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 block's end, even if an exception is raised on the way. It's equivalent to try-finally, but much shorter.

This will let you read, write and create the file if it don't exist:

f = open('filename.txt','a+')
f = open('filename.txt','r+')

Often used commands:

f.readline() #Read next line
f.seek(0) #Jump to beginning
f.read(0) #Read all file
f.write('test text') #Write 'test text' to file
f.close() #Close file

Sreetam Das's table is nice but needs a bit of an update according to w3schools and my own testing. Unsure if this due to the move to python 3.

"a" - Append - will append to the end of the file and will create a file if the specified file does not exist.

"w" - Write - will overwrite any existing content and will create a file if the specified file does not exist.

"x" - Create - will create a file, returns an error if the file exist.

I would have replied directly but I do not have the rep.

https://www.w3schools.com/python/python_file_write.asp

Related