在Python中先seek(),再read(),最后write()

7 投票
3 回答
24611 浏览
提问于 2025-04-15 11:13

当我运行以下的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和Python 2.6中都存在。
  3. 我通过再次调用seek()来绕过这个问题:

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

第二次调用seek()的实际参数似乎并不重要。

3 个回答

0

对我来说是可以的:

$ 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()

你是在用Windows吗?如果是的话,试试把模式中的 'r+' 改成 'rb+'

1

a+模式是用来追加内容的,如果你想要读和写,那你应该使用r+模式。

试试这个:

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

补充:

你应该一开始就说明你的平台……在Windows系统中,使用seek时会有已知的问题。因为在尝试定位时,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

5

这似乎是一个特定于Windows的问题 - 你可以查看这个链接 http://bugs.python.org/issue1521491,那里有类似的问题。

更好的是,有一个解决方法在这里解释过 http://mail.python.org/pipermail/python-bugs-list/2005-August/029886.html,你可以在:

f.seek(f.tell())

这段代码放在read()和write()调用之间。

撰写回答