运行以下python代码时:
>>> f = open(r"myfile.txt", "a+")
>>> f.seek(-1,2)
>>> f.read()
'a'
>>> f.write('\n')
我得到以下(有用的)异常:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 0] Error
用“r+”打开时也会发生同样的事情。
这应该失败吗?为什么?
编辑:
我通过再次调用seek()绕过了这个问题:
f = open(r"myfile.txt", "a+")
f.seek(-1,2)
f.read()
'a'
f.seek(-10,2)
f.write('\n')
第二个seek调用的实际参数似乎无关紧要。
这似乎是Windows特有的问题-有关类似问题,请参见http://bugs.python.org/issue1521491。
更好的是,在http://mail.python.org/pipermail/python-bugs-list/2005-August/029886.html中给出并解释了解决方法,插入:
在read()和write()调用之间。
对我有用:
你在窗户上吗?如果是,请尝试
'rb+'
,而不是'r+'
模式。a+模式用于追加,如果要读写,则需要r+。
试试这个:
编辑:
你应该先指定你的平台。。。在windows中查找存在已知问题。当试图寻找时,UNIX和Win32分别有不同的行尾LF和CRLF。读取文件结尾也有问题。我想您正在查找文件结尾的seek(2)偏移量,然后从那里继续。
您可能对这些文章感兴趣(第二篇更具体地说):
http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-08/2512.html
http://mail.python.org/pipermail/python-list/2002-June/150556.html
相关问题 更多 >
编程相关推荐