I know I can use io.StringIO or io.BytesIO to return an open file handle that can be written to and read from.
However, I'm looking for a way to make an in-memory region look like a named disk file that has not yet been opened.
The reason I want this is because there are routines which take the name of a disk file as an argument, and these routines then open the file and manipulate it. In some cases, I want the input or output for these routines to be a memory buffer, not a disk file, and for those routines, I can't pass an already-open file handle.
For example, one such routine is Image.save() from PIL, which expects a path name as its argument, not an already open file handle. When using that routine, I'd like the image data to be saved directly to a memory buffer, without any intermediate file IO being performed. There are also many other routines that take path names as arguments for which I would like this same behavior.
Is there any way to accomplish this in python?
Image.save()will happily take a file pointer in place of a filename, so you can useBytesIOwith it.Image.save()as an example.openand returning aBytesIOobject for special paths (however you define "special") rather than a file.Image.save(), it turns out that I have to previously set the name of the BytesIO buffer via something likebyteiobuffer.name = "foo.jpg", becauseImage.save()looks at thatnameattribute in order to get the image type.