我有这样的代码:
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为什么?我该怎么解决呢?
发布于 2017-07-04 09:18:32
您正在以"w"的形式打开该文件,它代表可写。
使用"w",您将无法读取文件。相反,请使用以下方法:
file = open("File.txt", "r")此外,以下是其他选项:
"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.发布于 2018-10-21 07:24:01
如果文件不存在,可以使用a+打开文件进行读取、写入和创建。
a+为追加和读取打开一个文件。如果文件存在,则文件指针位于文件的末尾。文件以附加模式打开。如果该文件不存在,它将创建一个用于读写的新文件。-Python文件模式
with open('"File.txt', 'a+') as file:
print(file.readlines())
file.write("test")注意:打开with块中的文件可以确保在块的末尾正确关闭文件,即使在途中引发异常也是如此。它相当于try-finally,但要短得多。
发布于 2017-07-04 09:17:57
打开文件的方式不多(读、写等)
如果您想从文件中读取,您应该键入file = open("File.txt","r"),如果是写而不是file = open("File.txt","w")。你需要对你的使用给予正确的许可。
更多模式:
https://stackoverflow.com/questions/44901806
复制相似问题