seek(),然后是read(),然后是python中的write() [英] seek(), then read(), then write() in python

查看:141
本文介绍了seek(),然后是read(),然后是python中的write()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在运行以下python代码时:

When running the following python code:

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

我得到以下(有用的)例外:

I get the following (helpful) exception:

Traceback (most recent call last):      
  File "<stdin>", line 1, in <module>   
IOError: [Errno 0] Error        

使用"r +"打开时,也会发生相同的情况.

The same thing happens when openning with "r+".

这应该失败吗?为什么?

Is this supposed to fail? Why?

  1. 显然,这只是一个例子,不是我实际上要执行的内容.我的实际目标是在添加新行之前验证文件以"\ n"结尾,或者添加一个.
  2. 我在Windows XP下工作,而Python 2.5和Python 2.6中都存在这些问题.
  3. 我设法通过再次调用seek()来绕过该问题:

  1. Obviously, this is just an example, not what I am actually trying to execute. My actual goal was to verify that the files ends with "\n", or add one, before adding the new lines.
  2. I am working under Windows XP, and they problem exists in both Python 2.5 and Python 2.6.
  3. I managed to bypass the problem by calling seek() again:

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

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

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

The actual parameters of the 2nd seek call don't seem to matter.

推荐答案

这似乎是Windows特有的问题-请参见

This appears to be a Windows-specific problem - see http://bugs.python.org/issue1521491 for a similar issue.

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

f.seek(f.tell())

在read()和write()之间.

between the read() and write() calls.

这篇关于seek(),然后是read(),然后是python中的write()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆