In the interest of not rewriting an open source library, I want to treat a string of text as a file in python 3.
Suppose I have the file contents as a stri
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
the other answers didn't work for me, but I managed to figure it out.
When using Python 3, you'll want to use io package.
import io
with io.StringIO("some initial text data") as f:
# now you can do things with f as if it was an opened file.
function_that_requires_a_Fileobject_as_argument(f)
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 io import StringIO for python 3
from StringIO 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