[Tutor] how to read from a txt file
jrlen balane
nbbalane at gmail.com
Tue Mar 15 01:36:10 CET 2005
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
print process(data)
=================
[1000]
==============
but this is what i have written on the text file:
1000
890
900
abc
500
650
850
1200
1100
On Tue, 15 Mar 2005 12:53:26 +1300, Liam Clarke <cyresse at gmail.com> wrote:
> Oops, and I meant
>
> try:
> tempLine = int(line)
>
> Silly indent error.
>
>
> On Tue, 15 Mar 2005 12:52:49 +1300, Liam Clarke <cyresse at gmail.com> wrote:
> > Well, a string "12345" when called through int() will come back as 12345.
> >
> > But, a string "foo", called through int(), will raise a TypeError.
> >
> > So....
> >
> > > 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:
> > > data_points.append(int(line))
> > > return data_points
> > >
> > > print process(data)
> >
> > You could do this
> >
> > 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)
> >
> > That's one way, but there's probably a better way.
> >
> > Regards,
> >
> > Liam Clarke
> > --
> > 'There is only one basic human right, and that is to do as you damn well please.
> > And with it comes the only basic human duty, to take the consequences.
> >
>
> --
> 'There is only one basic human right, and that is to do as you damn well please.
> And with it comes the only basic human duty, to take the consequences.
>
>
More information about the Tutor
mailing list