[Tutor] Read file line by line

Gilbert Tsang gtsang at lnxw.com
Wed Jan 26 02:33:55 CET 2005


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()

2 questions:
1. Why does the assignment-and-test in one line not allowed in Python? 
For example, while ((content = fd.readline()) != ""):
2. I know Perl is different, but there's just no equivalent of while 
($line = <A_FILE>) { } ? I'm not asking for Python has to offer Perl 
already has, but simply wondering a good way to read from a file 
line-by-line.

Regards, Gilbert.


More information about the Tutor mailing list