Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Input/Output, files

Tags:

python

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?

like image 529
Fire Lancer Avatar asked Dec 30 '22 08:12

Fire Lancer


1 Answers

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.

like image 136
Ned Batchelder Avatar answered Jan 04 '23 16:01

Ned Batchelder