Specific question about readlines versus xreadlines

Garry Knight garryknight at gmx.net
Thu Mar 18 02:18:03 CET 2004

Erik gave you the correct answer. I just thought I'd point out a few other
things about your code:

In message <c3aq2p$6v6$1 at news01.intel.com>, Pernell Williams wrote:

> #opening the file for reading
> str = 'myShortFile'

Did you know that str() is a Python function that returns the string
representation of an object. To see how it works, run Python interactively
and pass it some objects:
        print str(3)
        print str('hello')
        d = {"one": 1, "two": 2, "three": 3}
        print str(d)
In other words, it's not a good idea to redefine str in your code as it
hides the original function making it unusable. Also...

> file = open(str, 'r')

In Python file() is a function that happens to be an alias of open(). So if
you redefine it like this you can't do:
        f = file('myFile', 'r')
This is OK if you only intend to use open() but redefining existing Python
names is still arguably not good practice.

> while 1:
>   line = file.readline()
>   if line == '':
>     break

The usual way to read lines from a file is like this (assuming you followed
my previous suggestion and stopped using 'file' for the filename:
        for line in f.readlines():
          # process line
This will loop until line == '' so you don't even need the break statement.
And you can make it shorter still:
        for line in f:
          # process line
And you can shorten the whole process further still by combining the open
with the read:
        for line in open(filename):
          # process line

I realise that your example is specifically comparing and contrasting the
readline() function with the xreadlines() function, but I wasn't sure if
you were aware of the different ways of doing the same thing. If you were,
please ignore the above paragraph: hopefully it will prove useful to
newcomers to Python.

>   data = line
>   print data

I'm curious as to why you didn't just do 'print line' rather than assigning
it to 'data' first.

Garry Knight
garryknight at gmx.net  ICQ 126351135
Linux registered user 182025

More information about the Python-list mailing list