Ser*_*van 1 python variables file
我有什么方法可以将文件视为变量吗?作为一个例子,当调用从PIL Image模块保存的函数时:Image.save("foo.jpg")我希望所有数据都不保存在硬盘上但是要在变量中引入,a这样当a.read()调用它时,它应该返回文件内容的内容.是.
您可以使用BytesIO类将PIL图像保存到字节流.
>>> 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\ ...
Run Code Online (Sandbox Code Playgroud)
它可能值得阅读整个io模块页面,它很短,很多很好的信息,包含chioka指出的StringIO.
当然,看看StringIO模块.它为字符串提供了类似文件的接口.
http://docs.python.org/library/stringio.html
StringIO - File-like objects that read from or write to a string buffer.
Run Code Online (Sandbox Code Playgroud)