Luke
Luke

Reputation: 707

Let string act as file

I am working with a library that wants me to pass it data in the form of a file name. Then it will open that file and read the data. I have the data in a string, and I don't want to write it to a file (because I don't want to have to delete it afterwards).

Is there a way I can convert the string to a stream and generate a file name that will allow my library to open my stream and access the contents of my string?

Upvotes: 3

Views: 74

Answers (1)

Joran Beasley
Joran Beasley

Reputation: 114038

import tempfile

fh = tempfile.NamedTemporaryFile()  # this creates an actual file in the temp directory
fh.write(my_string)  
print fh.name
call_other_thing(fh.name)
fh.close()  # file is now deleted

Upvotes: 3

Related Questions