Thursday, March 3, 2011

Python Input/Output, files

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?

From stackoverflow
  • 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.

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

0 comments:

Post a Comment