4

I need to write some methods for loading/saving some classes to and from a binary file. However I also want to be able to accept the binary data from other places, such as a binary string.

In c++ I could do this by simply making my class methods use std::istream and std::ostream which could be a file, a stringstream, the console, whatever.

Does python have a similar input/output class which can be made to represent almost any form of i/o, or at least files and memory?

1
  • Classes -- themselves -- are Python bytecode, saved to files automatically by Python. You might be saving and restoring objects (instances of classes). If you mean objects, please rewrite your question to say objets or instances. Commented Nov 22, 2008 at 1:08

2 Answers 2

10

The Python way to do this is to accept an object that implements read() or write(). If you have a string, you can make this happen with StringIO:

from cStringIO import StringIO

s = "My very long string I want to read like a file"
file_like_string = StringIO(s)
data = file_like_string.read(10)

Remember that Python uses duck-typing: you don't have to involve a common base class. So long as your object implements read(), it can be read like a file.

Sign up to request clarification or add additional context in comments.

Comments

0

The Pickle and cPickle modules may also be helpful to you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.