[Tutor] how to read from a txt file

Kent Johnson kent37 at tds.net
Tue Mar 15 02:22:29 CET 2005


jrlen balane wrote:
> import sys
> 
> data_file = open('C:/Documents and Settings/nyer/Desktop/nyer.txt', 'r')
> data = data_file.readlines()
> 
> def process(list_of_lines):
>     data_points = []
>     for line in list_of_lines:
>         try:
>             tempLine = int(line)
>         except TypeError:
>             print "Non numeric character in line", line
>             continue #Breaks, and starts with next line
> 
>         data_points.append(tempLine)
>         return data_points
> 
> print process(data)
> 
> ==============
> 
> [1000]
> 
> ==============
> same result :( any other suggestion???

It doesn't look to me like you changed the 'return datapoints' line at all? Indentation is 
significant in Python; by indenting the 'return' past the 'for', you make the return part of the 
loop. The effect of this is to break out of the loop after the first line, which is what you are seeing.

Try this:

import sys

data_file = open('C:/Documents and Settings/nyer/Desktop/nyer.txt', 'r')
data = data_file.readlines()

def process(list_of_lines):
     data_points = []
     for line in list_of_lines:
         try:
               tempLine = int(line)
         except TypeError:
               print "Non numeric character in line", line
               continue #Breaks, and starts with next line

         data_points.append(tempLine)
     return data_points	#### This line was moved left four spaces
                         #### now it is not part of the loop

print process(data)

Kent
> 
> On Mon, 14 Mar 2005 19:57:26 -0500, Kent Johnson <kent37 at tds.net> wrote:
> 
>>jrlen balane wrote:
>>
>>>this is what i get after running this on IDLE:
>>>
>>>import sys
>>>
>>>data_file = open('C:/Documents and Settings/nyer/Desktop/nyer.txt', 'r')
>>>data = data_file.readlines()
>>>
>>>def process(list_of_lines):
>>>    data_points = []
>>>    for line in list_of_lines:
>>>        try:
>>>              tempLine = int(line)
>>>        except TypeError:
>>>              print "Non numeric character in line", line
>>>              continue #Breaks, and starts with next line
>>>
>>>        data_points.append(tempLine)
>>>        return data_points
>>
>>This line ^^^ is indented four spaces too much - you are returning after the first time through the
>>loop. Indent it the same as the for statement and it will work correctly.
>>
>>Kent
>>
>>>print process(data)
>>>
>>>=================
>>>[1000]
>>>
>>>==============
>>>but this is what i have written on the text file:
>>>
>>>1000
>>>890
>>>900
>>
>>_______________________________________________
>>Tutor maillist  -  Tutor at python.org
>>http://mail.python.org/mailman/listinfo/tutor
>>
> 
> 




More information about the Tutor mailing list