[Tutor] how to read from a txt file

Gregor Lingl glingl at aon.at
Thu Feb 17 10:49:38 CET 2005



Brian van den Broek schrieb:
> 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!

Unfortunately I read it. So I'll try a modest advice, too.
If I read "invalid literal for int" in the error-message,
I try out, what this literal is, by inserting one or two
simple print-statements ;-) :

def process(list_of_lines):
     data_points = []
     print list_of_lines
     for line in list_of_lines:
         print (line,)
         data_points.append(int(line))
     return data_points

Running the program n oe yields:

 >>>
1000

('1',)
('0',)
('0',)
('0',)
('\n',)

Traceback (most recent call last):
   File "C:/_/Tutorstuff/intprog.py", line 12, in -toplevel-
     print process(data)
   File "C:/_/Tutorstuff/intprog.py", line 6, in process
     data_points.append(int(line))
ValueError: invalid literal for int():
 >>>

which indicates, that your suspicion (readline - readlines)
was right

Regards
Gregor

> 
> 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
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

-- 
Gregor Lingl
Reisnerstrasse 3/19
A-1030 Wien

Telefon: +43 1 713 33 98
Mobil:   +43 664 140 35 27

Autor von "Python für Kids"
Website: python4kids.net


More information about the Tutor mailing list