[Tutor] how to read from a txt file

Brian van den Broek bvande at po-box.mcgill.ca
Sun Feb 13 20:32:18 CET 2005


Kent Johnson said unto the world upon 2005-02-13 14:04:
> 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 :-)

Gah! :-[   Outsmarting myself in public again. (At least I'm good at 
something :-) )

> 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

I do get that for the minimal logic I posted, this way is much 
simpler. But, isn't my way with a separate function more easily 
extended? (To deal with cases where there is more than just ints on 
lines, or where the data needs to be similarly processed multiple 
times, etc.)

I do feel a YAGNI coming on, though :-)

Anyway, thanks for improving my attempt to help.

Best,

Brian vdB


More information about the Tutor mailing list