[Tutor] how to read from a txt file
Liam Clarke
cyresse at gmail.com
Tue Mar 15 00:52:49 CET 2005
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.
More information about the Tutor
mailing list