file.readlines() - gives me error (bad file descriptor)

Binu K S binux.lists at gmail.com
Thu Jan 6 02:25:22 EST 2005


There's nothing crazy going on here. The file's current position moves
as you write into it. Both read and write operation use the same
offset. The tell() method gives you the current position at any time.
When you append to a file the position moves to the end of the file so
that the next write happens at the end. You normally wouldn't read
from the file that you are writing into. To read from the beginning,
change the position with seek. Here's how you do it:

>>> logfile=file(r'test.txt','a+')
>>> logfile.write('datetime')
>>> logfile.flush()
>>> test=logfile.readlines()
>>> print test
[]
>>> logfile.tell()
8L
>>> logfile.seek(0,0)
>>> test=logfile.readlines()
>>> print test
['datetime']


On Thu, 6 Jan 2005 12:30:03 +0530, Gurpreet Sachdeva
<gurpreet.sachdeva at gmail.com> wrote:
> logfile=file(r'test.txt','a+')
> logfile.write('datetime')
> logfile.flush()
> test=logfile.readlines()
> print test
> 
> I added logfile.flush(), the 'datetime' was written in the file
> correctly but I couldn't get any result...
> 
> Crazy!
> Garry
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list