Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python write in mkstemp() file

Tags:

python

mkstemp

I am creating a tmp file by using :

from tempfile import mkstemp

I am trying to write in this file :

tmp_file = mkstemp()
file = open(tmp_file, 'w')
file.write('TEST\n')

Indeed I close the file and do it proper but when I try to cat the tmp file, it stills empty..It looks basic but I don't know why it doesn't work, any explanations ?

like image 539
Steeven_b Avatar asked Jul 18 '16 12:07

Steeven_b


3 Answers

The answer by smarx opens the file by specifying path. It is, however, easier to specify fd instead. In that case the context manager closes the file descriptor automatically:

import os
from tempfile import mkstemp

fd, path = mkstemp()

# use a context manager to open (and close) file descriptor fd (which points to path)
with os.fdopen(fd, 'w') as f:
    f.write('TEST\n')

# This causes the file descriptor to be closed automatically
like image 121
Guido van Steen Avatar answered Oct 24 '22 04:10

Guido van Steen


mkstemp() returns a tuple with a file descriptor and a path. I think the issue is that you're writing to the wrong path. (You're writing to a path like '(5, "/some/path")'.) Your code should look something like this:

from tempfile import mkstemp

fd, path = mkstemp()

# use a context manager to open the file at that path and close it again
with open(path, 'w') as f:
    f.write('TEST\n')

# close the file descriptor
os.close(fd)
like image 23
user94559 Avatar answered Oct 24 '22 06:10

user94559


This example opens the Python file descriptor with os.fdopen to write cool stuff, then close it (at the end of the with context block). Other non-Python processes can use the file. And at the end, the file is deleted.

import os
from tempfile import mkstemp

fd, path = mkstemp()

with os.fdopen(fd, 'w') as fp:
    fp.write('cool stuff\n')

# Do something else with the file, e.g.
# os.system('cat ' + path)

# Delete the file
os.unlink(path)
like image 3
Mike T Avatar answered Oct 24 '22 06:10

Mike T