[Tutor] My first counter... is broken.
alan.gauld@bt.com
alan.gauld@bt.com
Thu, 8 Aug 2002 17:05:01 +0100
> Traceback (most recent call last):
> File
> "/home/sites/kmb/www/public_html/njindenial/counter.py", line 8,
> in ?
> number = int(number)
> ValueError: int() literal too large: 01213121412131215
>
> So I guess the number got too big to be an int()?
Lets look at that wjhats happening more closely:
First it reads 0 so adds 1 to get 1
It aopends the 1 to the file to get 01
It reads 01 to get 1, 1+1=2 and appends to the file: 012
It reads 012=12, 12+1=13, appends to file 01213
It reads 01213, 1213+1=1214, append = 012131214
It reads 012131214, add 1 to get 12131215, append = 1213121412131215
It tries the file but can't convert it coz its too big...
> ####################
> #! /usr/bin/python
> counter = open("counter.dat", "r+")
> number = counter.read()
This reads the whole file, try reading as lines with readlines()
> number = int(number)
then use slicing to get the last one:
number = int(numbers[-1]) # NB numbers to store the readlines()
> counter.write("%(number)s" % vars())
write adds to the end of the file but with no newline...
Use writeline() to write your number into a new line.
But since you probably don't want a file with an
incrementing number on each line a better way is
to use the seeek(0) call to rewind the file to the
beginning and overwrite the line each time, then
you can use readline() to just read a single line...
HTH,
Alan g.
Author of the 'Learning to Program' web site
http://www.freenetpages.co.uk/hp/alan.gauld