Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you convert file contents to a file object?

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)
like image 835
nickponline Avatar asked Dec 13 '25 18:12

nickponline


1 Answers

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.

like image 145
alecxe Avatar answered Dec 15 '25 06:12

alecxe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!