1

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.

2 Answers 2

8

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.

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

2 Comments

Thanks for the answer, it worked, but one more question, what is the purpose of 'im.write'?
That was me forgetting the proper Image class method to save for a bit, I've just removed :)
7

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.

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.