15

我得到了一个错误“IOError:[Errno 0] Error”这个python程序:

from sys import argv
file = open("test.txt", "a+")
print file.tell() # not at the EOF place, why?
print file.read() # 1
file.write("Some stuff will be written to this file.") # 2
# there r some errs when both 1 & 2
print file.tell()
file.close()

似乎是什么问题?以下这两种情况都可以:

from sys import argv
file = open("test.txt", "a+")
print file.tell() # not at the EOF place, why?
# print file.read() # 1
file.write("Some stuff will be written to this file.") # 2
# there r some errs when both 1 & 2
print file.tell()
file.close()

和:

from sys import argv
file = open("test.txt", "a+")
print file.tell() # not at the EOF place, why?
print file.read() # 1
# file.write("Some stuff will be written to this file.") # 2
# there r some errs when both 1 & 2
print file.tell()
file.close()

还是,为什么

print file.tell() # not at the EOF place, why?

不打印文件的大小,“a+”是附加模式吗?那么文件指针应该指向EOF吗?

我正在使用 Windows 7 和 Python 2.7。

4

2 回答 2

13

Python 使用 stdio 的 fopen 函数并将模式作为参数传递。我假设您使用 Windows,因为@Lev 说代码在 Linux 上运行良好。

以下来自windows的fopen文档,这可能是解决您问题的线索:

当指定“r+”、“w+”或“a+”访问类型时,允许读取和写入(文件被称为“更新”打开)。但是,当您在读取和写入之间切换时,必须有中间的 fflush、fsetpos、fseek 或 rewind 操作。如果需要,可以为 fsetpos 或 fseek 操作指定当前位置。

因此,解决方案是在调用file.seek()之前添加。file.write()要附加到文件末尾,请使用file.seek(0, 2).

供您参考,file.seek 的工作方式如下:

要更改文件对象的位置,请使用 f.seek(offset, from_what)。位置是通过将偏移量添加到参考点来计算的;参考点由 from_what 参数选择。from_what 值为 0 从文件开头测量,1 使用当前文件位置,2 使用文件末尾作为参考点。from_what 可以省略,默认为 0,使用文件的开头作为参考点。

[参考:http://docs.python.org/tutorial/inputoutput.html]

正如@lvc 在评论中和@Burkhan 在他的回答中提到的那样,您可以使用io 模块中较新的 open 函数。但是,我想指出,在这种情况下,write 函数的工作方式并不完全相同——您需要提供 unicode 字符串作为输入[只需u在您的情况下为字符串添加前缀 a]:

from io import open
fil = open('text.txt', 'a+')
fil.write('abc') # This fails
fil.write(u'abc') # This works

最后,请避免使用名称 'file' 作为变量名,因为它指的是内置类型并且会被静默覆盖,导致一些难以发现的错误。

于 2012-06-24T10:42:13.467 回答
6

解决方案是使用openfromio

D:\>python
Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('file.txt','a+')
>>> f.tell()
0L
>>> f.close()
>>> from io import open
>>> f = open('file.txt','a+')
>>> f.tell()
22L
于 2012-06-24T11:41:00.267 回答