【问题标题】:Python IOError: File not open for readingPython IOError:文件未打开以供读取
【发布时间】:2012-11-09 14:04:27
【问题描述】:

当我尝试在 Python 中打开文件时出现错误。这是我的代码:

>>> import os.path
>>> os.path.isfile('/path/to/file/t1.txt')
>>> True
>>> myfile = open('/path/to/file/t1.txt','w')
>>> myfile
>>> <open file '/path/to/file/t1.txt', mode 'w' at 0xb77a7338>
>>> myfile.readlines()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: File not open for reading

我也试过了:

for line in myfile:
    print(line)

我得到了同样的错误。有人知道为什么会出现这个错误吗?

【问题讨论】:

    标签: python file file-io


    【解决方案1】:

    您通过将模式指定为'w' 来打开文件进行写入;打开文件进行阅读:

    open(path, 'r')
    

    'r' 是默认值,所以可以省略。如果需要读写,请使用+模式:

    open(path, 'w+')
    

    w+ 打开文件进行写入(将其截断为 0 字节),但也允许您从中读取。如果你使用r+,它也可以读写,但不会被截断。

    如果您要使用r+w+等双模式,您还需要熟悉.seek() method,因为同时使用读取和写入操作会移动文件中的当前位置并您很可能希望在此类操作之间显式移动当前文件位置。

    有关详细信息,请参阅documentation of the open() function

    【讨论】:

    • 还要注意'r'是默认模式,不必明确给出。
    • @delnan:我已经在答案中明确表示了。
    • @MartijnPieters:谢谢,这是一个简单的错误
    【解决方案2】:

    如果你仔细想想,这是一个简单的错误。在您正在执行的代码中:

    myfile = open('/path/to/file/t1.txt','w')
    

    指定它是写的,你需要做的就是把它设置为读的r

    myfile = open('/path/to/file/t1.txt','r')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多