在python中,seek(),然后read(),然后write

2024-04-20 13:40:41 发布

您现在位置:Python中文网/ 问答频道 /正文

运行以下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+”打开时也会发生同样的事情。

这应该失败吗?为什么?

编辑:

  1. 显然,这只是一个例子,而不是我真正想要执行的。我的实际目标是在添加新行之前验证文件是否以“\n”结尾,或者添加一个。
  2. 我在Windows XP下工作,Python 2.5和python2.6都存在这个问题。
  3. 我通过再次调用seek()绕过了这个问题:

    f = open(r"myfile.txt", "a+")
    f.seek(-1,2)
    f.read()
    'a'
    f.seek(-10,2)
    f.write('\n')

第二个seek调用的实际参数似乎无关紧要。


Tags: 代码txtmostreadstdinlineseekopen
3条回答

这似乎是Windows特有的问题-有关类似问题,请参见http://bugs.python.org/issue1521491

更好的是,在http://mail.python.org/pipermail/python-bugs-list/2005-August/029886.html中给出并解释了解决方法,插入:

f.seek(f.tell())

在read()和write()调用之间。

对我有用:

$ echo hello > myfile.txt
$ python
Python 2.5.2 (r252:60911, Oct  5 2008, 19:24:49) 
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('myfile.txt', 'r+')
>>> f.seek(-1, 2)
>>> f.tell()
5L
>>> f.read()
'\n'
>>> f.write('\n')
>>> f.close()

你在窗户上吗?如果是,请尝试'rb+',而不是'r+'模式。

a+模式用于追加,如果要读写,则需要r+。

试试这个:

>>> f = open("myfile.txt", "r+")
>>> f.write('\n')

编辑:

你应该先指定你的平台。。。在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

相关问题 更多 >