Treat a string as a file in python

With what I can tell from your comments and recent edits, you want a file that can be opened using the open statement. (I'll leave my other answer be since it's the more correct approach to this type of question)

You can use tempfile to solve your problem, it basically is doing this: create your file, do stuff to your file, then delete your file upon closure.

import os
from tempfile import NamedTemporaryFile

f = NamedTemporaryFile(mode='w+', delete=False)
f.write("there is a lot of blah blah in this so-called file")
f.close()
with open(f.name, "r") as new_f:
    print(new_f.read())

os.unlink(f.name) # delete the file after

You can create a temporary file and pass its name to open:

On Unix:

tp = tempfile.NamedTemporaryFile()
tp.write(b'there is a lot of blah blah blah in this so-called file')
tp.flush()
open(tp.name, 'r')

On Windows, you need to close the temporary file before it can be opened:

tp = tempfile.NamedTemporaryFile(delete=False)
tp.write(b'there is a lot of blah blah blah in this so-called file')
tp.close()
open(tp.name, 'r')

You then become responsible for deleting the file once you're done using it.


StringIO returns an StringIO object, it's almost equivalent to the file object returned by the open statement. So basically, you can use the StringIO in place of the open statement.

# from StringIO import StringIO  # for Python 2, old
from io import StringIO
with StringIO('there is a lot of blah blah in this so-called file') as f:
    print(f.read())

Output:

there is a lot of blah blah in this so-called file

Tags:

Python

String

Io