[Tutor] how to read from a txt file

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Feb 17 10:44:19 CET 2005



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




More information about the Tutor mailing list