Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
909 views
in Technique[技术] by (71.8m points)

file io - seek(), then read(), then write() in python

When running the following python code:

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

I get the following (helpful) exception:

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

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

Is this supposed to fail? Why?

Edit:

  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 " ", 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 = open(r"myfile.txt", "a+")
    f.seek(-1,2)
    f.read()
    'a'
    f.seek(-10,2)
    f.write(' ')

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

Even better, a workaround given and explained at http://mail.python.org/pipermail/python-bugs-list/2005-August/029886.html, insert:

f.seek(f.tell())

between the read() and write() calls.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...