[Tutor] how to read from a txt file

Kent Johnson kent37 at tds.net
Mon Feb 14 02:02:06 CET 2005

jrlen balane wrote:
> and this line:
>      data_points.append(int(line))
> this would turn the string back to an integer, am i right?


> and on this one:
>     data_points = [ int(line) for line in data_file ]
> this did not use any read(), is this already equal to readline()? so
> this would already store all the data in the txt file to
> data_points[], am i right?

Yes. A handy feature of Python is that a file object is iterable - you can use a for loop or list 
comprehension to iterate over the lines of the file without an explicit readline(). So this:
   data_points = [ int(line) for line in data_file ]

is roughly equivalent to this (without the list comprehension):
   data_points = []
   for line in data_file:

or this (with explicit readline()):
   data_points = []
   while True:
     line = data_file.readline()
     if not line:

only the list comprehension is much more concise and, when you get used to it, much clearer.

> thank you guys! ei, you two are not competing, are you? anyway, hope
> its a friendly one. for the benifit of all those newbie like me,
> hehehe.

Definitely friendly.


More information about the Tutor mailing list