[Tutor] Newbie - Outputting List to a File [using shelve / long integers]

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Wed Oct 15 13:46:29 EDT 2003



On Sun, 12 Oct 2003, Matt Hehman wrote:

>  I was wondering if there was a way to save the list of primes generated
> to an output file so that I could just retrieve it and use it for the
> next number I tested.  I tried the .write command and received the error
> message:
>
> TypeError: argument 1 must be string or read-only character buffer, not
> list


Ah!  Try using the 'shelve' module: it provides persistant storage for
Python objects, and handles some of the low-level details of how to do it
efficiently.

    http://www.python.org/doc/lib/module-shelve.html

In particular, it deals with the details to convert live Python objects
into "character" bytes that can be written to disk.


Let's show a complete interactive session as a demonstration.  In the
first session, I'll generate a shelved object, and in the second, I'll try
retrieving that shelved object:

###
bash-2.05a$ python
Python 2.2 (#1, 11/12/02, 23:31:59)
[GCC Apple cpp-precomp 6.14] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> numbers = [42, 17, 3.1415926]
>>> import shelve
>>> d = shelve.open('storage')
>>> d['numbers'] = numbers
>>> d.close()
###

That's the first session.  Let's see if we can get back our numbers now:



###
bash-2.05a$ python
Python 2.2 (#1, 11/12/02, 23:31:59)
[GCC Apple cpp-precomp 6.14] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import shelve
>>> d = shelve.open('storage')
>>> numbers = d['numbers']
>>> numbers
[42, 17, 3.1415926000000001]
###


Try it out, and feel free to ask more questions about shelve; it's very
nice for saving the state of Python objects.



> Also, I started playing around with increasingly large numbers, is there
> anything I need to do to accomodate that?

If you're using large integers, you should be fine --- Python will
automagically promote an integer into a "long int" if it goes beyond the
range of a normal 32-bit integer.  For example, it's easy to do 2 to the
40'th power:

###
>>> 2**40
1099511627776L
###

The trailing 'L' at the end there tells us that Python is using
long-integers to represent the number, since it's too large to store using
a hardware representation.

Good luck!




More information about the Tutor mailing list