[Tutor] how to read from a txt file

Brian van den Broek bvande at po-box.mcgill.ca
Thu Feb 17 09:51:07 CET 2005


jrlen balane said unto the world upon 2005-02-17 02:41:
> sir, what seemed to be the problem with this:
> 
> def process(list_of_lines):
>     data_points = []
>     for line in list_of_lines:
>         data_points.append(int(line))
>     return data_points
> 
> data_file = open('C:/Documents and Settings/nyer/Desktop/nyer.txt', 'r')
> data = data_file.readline()
> 
> print process(data)
> 
> 
> here is what is written in the nyer.txt:
> 1000
> 890
> 900
> 500
> 650
> 850
> 1200
> 1100
> 
> what i want is to print data_points:
> and this is the error:
> 
> Traceback (most recent call last):
>   File "C:\Python23\practices\opentxt", line 12, in -toplevel-
>     process(data)
>   File "C:\Python23\practices\opentxt", line 6, in process
>     data_points.append(int(line))
> ValueError: invalid literal for int(): 

Hi,

I think the traceback is my fault from an oversight in the code I sent 
you when you posted before. Sorry about that :-[

There are two problems with your code.

The immediate one, due to my advice, is that each line of your file 
ends with a newline character ('\n'). So, you cannot call int on '1000\n'.

Try
data_points.append(int(line[:-1]))
instead. That will call int on line minus the last character (the 
newline).
  	
The other problem is that you use data = data_file.readline(). That 
will give you a single line each time you call it. If you stick with 
this approach, I think you want data = data_file.readlines() (note the 
's' at the end.)

But, you might do well to consider some of the other suggestions you 
got. They came from more capable programmers than me!

Best,

Brian vdB



More information about the Tutor mailing list