Is there any way I can make so that I can treat a file as a variable?
As an example when the function save from PIL Image module is called: Image.save("foo.jpg") i would like all the data not to save on the hard disk but to be introduced in a variable a so that when a.read() is called, it should return what the content of the file would be.
Add a comment
|
2 Answers
You can use the BytesIO class to save a PIL Image to a byte stream.
>>> from PIL import Image
>>> im = Image.open('ball.png')
>>> from io import BytesIO
>>> buffer = BytesIO()
>>> im.save(buffer, format='png')
>>> buffer.getvalue()
'\x89PNG\r\n\x1a\n\x00\ ...
It's probably worth reading through the whole io module page, it's pretty short, lots of good info, contains StringIO as ch3ka pointed out.
2 Comments
Serban Razvan
Thanks for the answer, it worked, but one more question, what is the purpose of 'im.write'?
Andrew Barrett
That was me forgetting the proper Image class method to save for a bit, I've just removed :)
sure, take a look in the StringIO module. It provides a file-like interface for strings.
http://docs.python.org/library/stringio.html
StringIO - File-like objects that read from or write to a string buffer.