[Tutor] My first counter... is broken.

Yigal Duppen yduppen@xs4all.nl
Thu, 8 Aug 2002 14:12:36 +0200


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

> ValueError: int() literal too large: 01213121412131215
>
> So I guess the number got too big to be an int()?  But it should have
> been counting by 1's not jumping around into hundreds and thousands.
> Here is my code:
>
> counter = open("counter.dat", "r+")
> number = counter.read()
> number = int(number)
> number = number + 1
> counter.write("%(number)s" % vars())
> counter.close()

What happens here is that each new number is _appended_ to the 'counter.dat' 
file.
So, in successive runs, the following will happen:
1.	read 0, write 1
2.	read 01, write 2
3.	read 012, write 13
4.	read 01213, write 1214
5.	read 012131214, write 01213121412131215
6.	read and boom; note how the number corresponds exactly to your error

So there are two options:
1. 	after reading, go back to the beginning using counter.seek(0)
2.	separate reading from writing as follows:

# reading
counter = open("counter.dat", "r")
number = int(counter.read()) + 1
counter.close()

# writing
counter = open("counter.dat", "w")
counter.write(str(number))
counter.close()

- -- 
http://www.xs4all.nl/~yduppen
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.7 (GNU/Linux)

iD8DBQE9UmA0LsKMuCf5EdwRApamAJ0cjfpoBFr7woIzGNtV8FfrnTRRdgCg4C5Q
qLt8mNAUGAjPyvqXIQ3cnhc=
=zJrl
-----END PGP SIGNATURE-----