[Tutor] how to read from a txt file

Brian van den Broek bvande at po-box.mcgill.ca
Thu Feb 17 10:18:23 CET 2005


Brian van den Broek said unto the world upon 2005-02-17 03:51:

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

<SNIP>

>> 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(): 


> 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'.

Bollocks! Nobody read any thing I write where I am claiming to answer 
anyone!

IDLE 1.1
 >>> int('1000\n')
1000
 >>>

So, sorry, I don't know what's wrong with the code you sent me, and I 
fear that if I tried to work it out, I'd do more damage. I yield the 
floor as I am off to write "Don't post untested code 1000 times.

(I will say I suspect it is the readline vs. readlines, but then 
hopefully no one is reading this ;-)

Sheepishly,

bran vdB



More information about the Tutor mailing list