Python变量和文件 [英] Python variables and files
本文介绍了Python变量和文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
作为一个例子,当调用从PIL Image模块保存的函数时:
Image.save(foo.jpg)
我想要所有的数据不是保存在硬盘上,而是在变量 a
中引入,这样当 a.read()
被调用,它应该返回文件的内容。解决方案
您可以使用 BytesIO 类将PIL Image保存为字节流。
>>>从PIL导入Image
>>> im = Image.open('ball.png')
>>> from io import BytesIO
>>> buffer = BytesIO()
>>> im.save(buffer,format ='png')
>>> buffer.getvalue()
'\x89PNG\r\\\
\x1a\\\
\x00\ ...
可能值得通读整个 io模块页面,它很短,很多很好的信息,包含String3 ch3ka指出。
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.
解决方案
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.
这篇关于Python变量和文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文