Aswin Murugesh
Aswin Murugesh

Reputation: 11070

output an object to a file using python

I want to know how i can store a class object in a file so as to retrive it later. eg) I have a stack class and i need to store the object of that class to retrive it later. I tried the following:

output_file=open('hello.txt','w')
output_file.write(x)

Where x is the object of the stack class. The whole stack program works well and when i come to this storing part, i get an error as:

Traceback (most recent call last):
File "class.py", line 32, in <module>
    output_file.write(x)
TypeError: expected a character buffer object

How can i correct this mistake? what is the best way to store?

Upvotes: 2

Views: 880

Answers (2)

Ceasar
Ceasar

Reputation: 23083

Either use pickle as suggested or coerce the object to a str, which is what write is expecting.

Note, if you decide to coerce to a str and want to recover the object, you'll need to overwrite __str__ in the object you are serializing to output enough data to reconstruct the object.

Upvotes: 1

NPE
NPE

Reputation: 500475

The easiest is to use the pickle module.

There are some examples in the manual.

Upvotes: 3

Related Questions