[Tutor] how to read from a txt file

jrlen balane nbbalane at gmail.com
Tue Mar 15 02:06:05 CET 2005


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???

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