[Tutor] how to read from a txt file

Kent Johnson kent37 at tds.net
Tue Mar 15 01:57:26 CET 2005


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



More information about the Tutor mailing list