gpt4 book ai didi

Python IOError : File not open for reading

转载 作者:IT老高 更新时间:2023-10-28 20:38:08 27 4
gpt4 key购买 nike

当我尝试在 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)

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

最佳答案

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

open(path, 'r')

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

open(path, 'w+')

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

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

documentation of the open() function了解更多详情。

关于Python IOError : File not open for reading,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13309548/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com