Python 错误消息 io.Unsupport tedOperation: 不可读

我有这个密码:

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

但是当我尝试它时,我会得到一个错误消息,比如:

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

UnsupportedOperation: not readable

为什么,我该怎么补救?

214719 次浏览

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

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

Using "w" you won't 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 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