read files
Benjamin
musiccomposition at gmail.com
Mon Jan 21 22:11:15 EST 2008
On Jan 21, 9:08 pm, Mel <mwil... at the-wire.com> wrote:
> 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
more idiomatic in Python 2.5+:
from __future__ import with_statement
with open("/my/file.conf") as fd:
for line in fd:
print line
>
> Mel.
More information about the Python-list
mailing list