简体   繁体   English

写入内存文件而不是文件路径

[英]Writing to a memory file instead of file path

Is it possible to supply a path to the buffer where to write the data instead of supplying a file path eg instead of object.save("D:\\filename.jpg") supply it a path to memory buffer.是否可以提供写入数据的缓冲区路径而不是提供文件路径,例如代替object.save("D:\\filename.jpg")为其提供内存缓冲区的路径。 I want to do this to avoid writing the image object data to file as .JPG and save it directly into memory so that I can have it in memory rather than loading it again from disk.我想这样做是为了避免将图像对象数据以.JPG格式写入文件并将其直接保存到内存中,以便我可以将其保存在内存中,而不是从磁盘再次加载它。

我相信您正在寻找StringIO库。

If you want a raw buffer of bytes to write to, use bitstring .如果您想要写入字节的原始缓冲区,请使用bitstring

>>> a = BitArray('0x1af')
>>> a.hex, a.bin, a.uint     # Different interpretations using properties
('1af', '000110101111', 431)

If you don't want a raw array of bits/bytes, then just keep your image object in memory.如果您不想要原始的位/字节数组,那么只需将您的图像对象保存在内存中。 It's basically the same thing as a file, just, as you say -- in memory not on disk.它与文件基本上是一样的,就像你说的——在内存中而不是在磁盘上。

If object.save supports file-like objects, that means, objects, that have a write-method, you can provide the method with a StringIO.StringIO instance.如果object.save支持类文件对象,即具有写入方法的对象,则可以为该方法提供StringIO.StringIO实例。 It has the same interface as a normal file-object, but keeps its contents in memory.它具有与普通文件对象相同的接口,但将其内容保存在内存中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM