"pickle" vs. f.write()

J

Johan Kohler

Hi,

I have a class with attributes that are string, integer and list. eg.

class person:
name =""
age = 0
friends=[]
comment=""""""

me = person()

I want to save a whole bunch of instances to a file, a classic "records"
file I/O.

To write the file, I can do f.write(str([me.name, me.age, me.friends,
me.comment]) + "\n"

This works nicely for writing, but when reading, I cannot convert the
string easily to a list:
list(f.readline()) is not the same as [me.name, me.age, me.friends,
me.comment]

I was wondering whether pickle might make this easier - an example would
be much appreciated.

Otherwise, what is the best "Python" way to write and read this data
structure?

Thanks in advance...

Johan

__
Yes, I do feel stupid asking this, but time's-a-runnin' out..
 
P

Peter Maas

Johan said:
class person:
name =""
age = 0
friends=[]
comment=""""""

me = person()

Otherwise, what is the best "Python" way to write and read this data
structure?

import pickle

class person:
name =""
age = 0
friends=[]
comment=""""""

me = person()

# store
pf = file('/tmp/pickletest', 'w')
pickle.dump(me, pf)
pf.close()


# load
pf = file('/tmp/pickletest', 'r')
me2 = pickle.load(pf)
pf.close()

This is sequential access. If you want to have random access, look
for shelve.
 
J

Johan Kohler

Thanks... works like a charm :)

Johan said:
class person:
name =""
age = 0
friends=[]
comment=""""""
me = person()
Otherwise, what is the best "Python" way to write and read this data
structure?

import pickle

class person:
name =""
age = 0
friends=[]
comment=""""""

me = person()

# store
pf = file('/tmp/pickletest', 'w')
pickle.dump(me, pf)
pf.close()


# load
pf = file('/tmp/pickletest', 'r')
me2 = pickle.load(pf)
pf.close()

This is sequential access. If you want to have random access, look
for shelve.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Pickle 0
pickle module doens't work 9
Problem with pickle and restarting a program 3
Pickle a list 1
Pickle MemoryError - any ideas? 3
Python Pickle 1
writing pickle function 6
cPickle vs pickle discrepancy 0

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top