readline()/readlines() inconsistent?

Quinn Dunkan quinn at retch.ugcs.caltech.edu
Sun Jul 8 22:40:23 EDT 2001


On Mon, 09 Jul 2001 00:43:02 GMT, Tim Hammerquist <tim at vegeta.ath.cx> wrote:
>Carsten Gaebler <clpy at snakefarm.org> wrote:
>> Hi there!
>> 
>> I've just come across a strange difference between readline() and
>> readlines():
>> 
>> Python 2.1 (#17, Jun 15 2001, 15:24:30) 
>> [GCC 2.95.2 19991024 (release)] on linux2
>> Type "copyright", "credits" or "license" for more information.
>> >>> f = open("foobar", "w")
>> >>> f.readline()
>> ''
>> >>> f.close()
>> >>> 
>> >>> f =  open("foobar", "w")
>> >>> f.readlines()
>> Traceback (most recent call last):
>>   File "<stdin>", line 1, in ?
>> IOError: [Errno 9] Bad file descriptor
>> >>> 
>
>Same happens on my box.
>
>$ cat /proc/version
>Linux version 2.2.15-4mdk (chmou at kenobi.mandrakesoft.com)
>(gcc version 2.95.3 19991030 (prerelease)) #1 Wed May 10 15:31:30 CEST 2000
>
>$ python
>Python 2.0 (#1, Oct 16 2000, 18:10:03) 
>[GCC 2.95.2 19991024 (release)] on linux2
>[ snip ]
>
>BTW, is file.xreadlines() a new feature in Py2.1?

Yep.

>Of course, an obvious question is, if you want to read _and_ write, why
>weren't you using 'r+' or 'w+' to begin with?
>
>I hope someone can answer this, but is this a matter of file I/O
>implementation between different OS's?  Or is this a Python
>implementation issue?

Despite what the documentation may say, readlines does not use readline.
readlines uses fread() (since it doesn't have to worry about reading too much)
and then checks with ferror().  readline uses getc() (or perhaps fgets()) and,
when it gets EOF for error, proceeds to *not* check for error (clears it, in
fact).  So I'd say linux, SunOS, and Irix are correct here and OSX is wrong
(must not be reporting via ferror() correctly).

I'd say python is wrong here too, by not being consistent.  If readline
checks, readlines should too.



More information about the Python-list mailing list