I have a function the expects a file object, simplified example:
def process(fd):
print fd.read()
which would normally be called as:
fd = open('myfile', mode='r')
process(fd)
I can't change this function, and I already have the contents of the file in memory. Is there any way to convert the file contents into a file object without writing it to disk so I could do something like this:
contents = 'The quick brown file'
fd = convert(contents) # ??
process(fd)
You can do this using StringIO:
This module implements a file-like class, StringIO, that reads and writes a string buffer (also known as memory files).
from StringIO import StringIO
def process(fd):
print fd.read()
contents = 'The quick brown file'
buffer = StringIO()
buffer.write(contents)
buffer.seek(0)
process(buffer) # prints "The quick brown file"
Note that in Python 3 it was moved into io package - you should use from io import StringIO instead of from StringIO import StringIO.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With