reading a text file
Peter Otten
__peter__ at web.de
Wed Aug 19 05:08:06 EDT 2009
superpollo wrote:
> hi clp
>
> what's the difference between:
>
> while True:
> input_line = sys.stdin.readline()
> if input_line:
> sys.stdout.write(input_line.upper())
> else:
> break
>
> and:
>
>
> while True:
> try:
> sys.stdout.write(sys.stdin.next().upper())
> except StopIteration:
> break
You should write the latter as
for line in sys.stdin:
sys.stdout.write(line.upper())
or
sys.stdout.writelines(line.upper() for line in sys.stdin)
You seem to know already that next() and readline() use different ways to
signal "I'm done with the file". Also, after the first StopIteration
subsequent next() calls are guaranteed to raise a StopIteration. But the
main difference is that file.next() uses an internal buffer, file.readline()
doesn't. That means you would lose data if you tried to replace the
readline() call below with next()
first_line = f.readline()
read_of_the_file = f.read()
In newer Python versions you will get a ValueError when mixing next() and
read()/readline() but in older Pythons (before 2.5 I think) you are in for a
surprise.
As
for line in file: ...
is both the fastest and most readable approach if you want to access a file
one line at a time I recommend that you use it unless there is a specific
reason not to.
Peter
More information about the Python-list
mailing list