【问题标题】:Python error message io.UnsupportedOperation: not readablePython 错误信息 io.UnsupportedOperation: not readable
【发布时间】:2017-12-07 16:20:18
【问题描述】:

我做了一个简单的程序,但运行时显示以下错误:

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

它显示了这个错误信息:

文件“C:/Users/Sachin Patil/fourth,py.py”,第 18 行,在
对于文件中的行:

UnsupportedOperation:不可读

【问题讨论】:

  • 好吧,您没有授予文件读取权限。但是在这里这样做是没有用的,因为光标将位于文件的末尾。
  • 我尝试了搜索功能,但它不起作用,您所说的读取权限是什么意思?

标签: python-3.x file


【解决方案1】:

您以"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.

【讨论】:

    【解决方案2】:

    使用a+打开一个文件进行读取、写入,如果它不存在则创建它。

    a+ 打开一个文件以进行追加和读取。文件指针位于 如果文件存在,则文件末尾。该文件在追加中打开 模式。如果文件不存在,则创建一个新文件以供读取 和写作。 -Python file modes

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

    注意:with 块中打开文件确保文件在块的末尾正确关闭,即使在途中引发异常也是如此。它相当于try-finally,但要短得多。

    【讨论】:

      【解决方案3】:

      有几种打开文件的模式(读、写等)

      如果你想从文件中读取你应该输入file = open("File.txt","r"),如果写比file = open("File.txt","w")。您需要对您的使用给予正确的许可。

      更多模式:

      • r。打开一个只读文件。
      • RB。以二进制格式打开一个只读文件。
      • r+ 打开一个文件进行读写。
      • rb+ 以二进制格式打开一个文件进行读写。
      • w。打开一个仅用于写入的文件。
      • 您可以在here找到更多模式

      【讨论】:

        【解决方案4】:

        如果文件不存在,这将让您读取、写入和创建文件:

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

        常用命令:

        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
        

        【讨论】:

          【解决方案5】:

          Sreetam Das 的表不错,但根据 w3schools 和我自己的测试需要进行一些更新。不确定这是否是因为迁移到 python 3。

          “a” - Append - 将追加到文件的末尾,如果指定的文件不存在,将创建一个文件。

          “w” - 写入 - 将覆盖任何现有内容,如果指定的文件不存在,将创建一个文件。

          "x" - 创建 - 将创建一个文件,如果文件存在则返回错误。

          我会直接回复,但我没有代表。

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

          【讨论】:

            猜你喜欢
            • 2015-06-14
            • 2018-02-17
            • 1970-01-01
            • 1970-01-01
            • 2013-09-28
            • 2013-05-04
            • 2021-05-30
            • 1970-01-01
            相关资源
            最近更新 更多