Python IOError:文件未打开以供阅读

Ali*_*a41 21 python file-io file

当我尝试在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
Run Code Online (Sandbox Code Playgroud)

我也尝试过:

for line in myfile:
    print(line)
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*ers 43

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

open(path, 'r')
Run Code Online (Sandbox Code Playgroud)

'r'是默认值,因此可以省略.如果您需要同时读写,请使用以下+模式:

open(path, 'w+')
Run Code Online (Sandbox Code Playgroud)

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

如果你要使用r+or 等双模式w+,你也需要熟悉这个.seek()方法,因为同时使用读取和写入操作会移动文件中的当前位置,你很可能想要移动当前文件在这些操作之间明确定位.

有关更多详细信息,请参阅该函数文档open().