[Tutor] how to read from a txt file

jrlen balane nbbalane at gmail.com
Tue Mar 15 00:29:25 CET 2005


say i have the code that reads decimal value from a text file:

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)

====================
what if, on the text file, a user has encoded values other than
decimal, how would i add a code that would act like an Exception, or
would tell the user that there is an invalid entry in the text file,
like a "letter or other character other than number" ?


On Thu, 17 Feb 2005 01:44:19 -0800 (PST), Danny Yoo
<dyoo at hkn.eecs.berkeley.edu> wrote:
> 
> 
> > >> 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 Brian,
> 
> Ah, think about empty lines.
> 
> Let's look at the error message again:
> 
>     ValueError: invalid literal for int():
>                                           ^^^^^^^
> 
> There's nothing visible there after the colon, and that's our hint.
> Notice what happens when we pass int()  some wacky strings:
> 
> ###
> >>> int("foobar")
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> ValueError: invalid literal for int(): foobar
> ###
> 
> So whatever is being passed to int() should show up in the error message.
> This is exactly why getting literal error messages is so wonderful.
> *grin*
> 
> Since we don't see anything here:
> 
> > >>   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():
> 
> my best guess is that there's an empty line in the file, since we get the
> same kind of error if we do this:
> 
> ###
> >>> int("")
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> ValueError: invalid literal for int():
> ###
> 
> Best of wishes to you!
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


More information about the Tutor mailing list