[Tutor] Read file line by line

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Wed Jan 26 02:51:26 CET 2005



On Tue, 25 Jan 2005, Gilbert Tsang wrote:

> Hey you Python coders out there:
>
> Being a Python newbie, I have this question while trying to write a
> script to process lines from a text file line-by-line:
>
> #!/usr/bin/python
> fd = open( "test.txt" )
> content = fd.readline()
> while (content != "" ):
>     content.replace( "\n", "" )
>     # process content
>     content = fd.readline()
>
> 1. Why does the assignment-and-test in one line not allowed in Python?
> For example, while ((content = fd.readline()) != ""):


Hi Gilbert, welcome aboard!

Python's design is to make statements like assignment stand out in the
source code.  This is different from Perl, C, and several other languages,
but I think it's the right thing in Python's case.  By making it a
statement, we can visually scan by eye for assignments with ease.


There's nothing that really technically prevents us from doing an
assignment as an expression, but Python's language designer decided that
it encouraged a style of programming that made code harder to maintain.
By making it a statement, it removes the possiblity of making a mistake
like:

###
if ((ch = getch()) = 'q') { ... }
###



There are workarounds that try to reintroduce assignment as an expression:

    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/202234

but we strongly recommend you don't use it.  *grin*




> 2. I know Perl is different, but there's just no equivalent of while
> ($line = <A_FILE>) { } ?

Python's 'for' loop has built-in knowledge about "iterable" objects, and
that includes files.  Try using:

    for line in file:
        ...

which should do the trick.


Hope this helps!



More information about the Tutor mailing list