create & read from tempfile
Is there anyway I could write to tempfile and include it in a command, and then close/remove it. I would like to execute the command, eg: some_command /tmp/some-temp-file.
Many thanks in advance.
import tempfile
temp = tempfile.TemporaryFile()
temp.write('Some data')
command=(some_command temp.name)
temp.close()
Solution 1:
Complete example.
import tempfile
with tempfile.NamedTemporaryFile() as temp:
temp.write('Some data')
if should_call_some_python_function_that_will_read_the_file():
temp.seek(0)
some_python_function(temp)
elif should_call_external_command():
temp.flush()
subprocess.call(["wc", temp.name])
Update: As mentioned in the comments, this may not work in windows. Use this solution for windows
Update 2: Python3 requires that the string to be written is represented as bytes, not str, so do instead
temp.write(bytes('Some data', encoding = 'utf-8'))
Solution 2:
If you need a temporary file with a name you have to use the NamedTemporaryFile
function. Then you can use temp.name
. Read
http://docs.python.org/library/tempfile.html for details.