Python Input / Output files

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

In C ++, I could do this simply by using the methods of the std :: istream and std :: ostream class, which can be a file, line, console, whatever.

Does python have a similar I / O class that can be represented to represent almost any form of I / O, or at least files and memory?

+4
source share
2 answers

Python's way of doing this is to accept an object that implements read () or write (). If you have a string, you can do this 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 printing: you do not need to include a common base class. As long as your object implements read (), it can be read as a file.

+10
source

Pickle and cPickle modules may also be useful for you.

0
source

All Articles