Python文件操作

ims*_*rch 14 python file-io

我用这个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()
Run Code Online (Sandbox Code Playgroud)

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

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()
Run Code Online (Sandbox Code Playgroud)

和:

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()
Run Code Online (Sandbox Code Playgroud)

仍然,为什么

print file.tell() # not at the EOF place, why?
Run Code Online (Sandbox Code Playgroud)

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

我正在使用Windows 7和Python 2.7.

Dha*_*ara 11

Python使用stdio的fopen函数并将模式作为参数传递.我假设你使用windows,因为@Lev说代码在Linux上工作正常.

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

当指定"r +","w +"或"a +"访问类型时,允许读取和写入(该文件被称为"更新"打开).但是,当您在读取和写入之间切换时,必须进行干预fflush,fsetpos,fseek或倒带操作.如果需要,可以为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模块中较新的开放功能.但是,我想指出在这种情况下write函数不能完全相同 - 你需要提供unicode字符串作为输入[只需u在你的情况下为字符串添加前缀]:

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

最后,请避免使用名称"file"作为变量名称,因为它引用了内置类型并且将被静默覆盖,导致一些难以发现的错误.


Bur*_*lid 6

该解决方案是使用openio

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
Run Code Online (Sandbox Code Playgroud)