小编典典

Python文件操作

python

我在此python程序中遇到了一个错误“ IOError:[Errno 0] Error”:

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。


阅读 217

收藏
2020-12-20

共1个答案

小编典典

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](http://docs.python.org/tutorial/inputoutput.html):[//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”用作变量名,因为它指的是内置类型,并且会被静默覆盖,从而导致一些难以发现的错误。

2020-12-20