[Tutor] how to read from a txt file

Kent Johnson kent37 at tds.net
Sun Feb 13 20:04:04 CET 2005


Brian van den Broek wrote:
> Since you files are quite short, I'd do something like:
> 
> <code>
> data_file = open(thedata.txt, 'r') # note -- 'r' not r
> data = data_file.readlines()       # returns a list of lines
> 
> def process(list_of_lines):
>     data_points = []
>     for line in list_of_lines:
>         data_points.append(int(line))
>     return data_points
> 
> process(data)

This can be done much more simply with a list comprehension using Python's ability to iterate an 
open file directly:
data_file = open('thedata.txt', 'r') # note -- 'thedata.txt' not thedata.txt :-)
data_points = [ int(line) for line in data_file ]

then process the data with something like
for val in data_points:
   # do something with val
   time.sleep(300)

Alternately (and my preference) the processing could be done in the read loop like this:
data_file = open('thedata.txt', 'r')
for line in data_file:
   val = int(line)
   # do something with val
   time.sleep(300)

Kent

> </code>
> 
> This assumes that each line of the data file has nothing but a string 
> with an int followed by '\n' (for end of line), and that all you need is 
> a list of those integers. Maybe these are bad assumptions -- but they 
> might get you started.
> 
> HTH,
> 
> Brian vdB
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



More information about the Tutor mailing list