read files

Mel mwilson at the-wire.com
Tue Jan 22 04:08:02 CET 2008


J. Peng wrote:
> first I know this is the correct method to read and print a file:
> 
> fd = open("/etc/sysctl.conf")
> done=0
> while not done:
>     line = fd.readline()
>     if line == '':
>         done = 1
>     else:
>         print line,
> 
> fd.close()
> 
> 
> I dont like that flag of "done",then I tried to re-write it as:
> 
> fd = open("/etc/sysctl.conf")
> while line = fd.readline():
>     print line,
> fd.close()
> 
> 
> this can't work.why?

Formally, because line = fd.readline() is a statement, not an
expression, and it can't be put into an if statement like that.

The most idiomatic way is probably


fd = open ("/etc/sysctl.conf")
for line in fd:
    print line



	Mel.



More information about the Python-list mailing list