Python IOError:文件未打开以供读取 [英] Python IOError: File not open for reading

查看:95
本文介绍了Python IOError:文件未打开以供读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I get an error when I try to open a file in Python. Here is my code :

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

,我遇到了同样的错误.有人知道为什么会发生此错误吗?

and I got the same error. Does anybody know why this error occurs?

推荐答案

通过将模式指定为'w'可以打开文件进行写入.而是打开文件进行读取:

You opened the file for writing by specifying the mode as 'w'; open the file for reading instead:

open(path, 'r')

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

'r' is the default, so it can be omitted. If you need to both read and write, use the + mode:

open(path, 'w+')

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

w+ opens the file for writing (truncates it to 0 bytes) but also lets you read from it. If you use r+ it is also opened for both reading and writing, but won't be truncated.

如果要使用r+w+之类的双模式,则需要熟悉

If you are to use a dual-mode such as r+ or w+, you need to familiarize yourself with the .seek() method too, as using both reading and writing operations will move the current position in the file and you'll most likely want to move that current file position explicitly between such operations.

有关详细信息,请参见open()函数的文档

See the documentation of the open() function for further details.

这篇关于Python IOError:文件未打开以供读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆