Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Temporary file with specific file extension in Python 3

I am writing some unit tests for a piece of code that takes a path and attempts to load the file if it has a known extension, then does more careful checking.

In the unit test, I would like to create a temporary file that has the correct extension, but incorrect contents, in my case an empty file posing as test.tif.

How can I create a temporary file while specifying the extension (or the entire name), using the tempfile module?

I have looked at the NamedTemporaryFile class, as well as the suffix and prefix parameters, but I still cannot set the extension. I suppose I could manually create a file in a temporary directory, but then I loose the self-deleting capability that I am after.

like image 359
Benjamin Avatar asked Aug 11 '16 15:08

Benjamin


People also ask

How do I use temp files in Python?

If you want to write text data into a temp file, you can use the writelines() method instead. For using this method, we need to create the tempfile using w+t mode instead of the default w+b mode. To do this, a mode param can be passed to TemporaryFile() to change the mode of the created temp file.

What does Tempfile Mkdtemp return?

mkdtemp() returns the absolute pathname of the new directory. Raises an auditing event tempfile. mkdtemp with argument fullpath . Changed in version 3.5: suffix, prefix, and dir may now be supplied in bytes in order to obtain a bytes return value.

What is TMP in Python?

The tempfile module in standard library defines functions for creating temporary files and directories. They are created in special temp directories that are defined by operating system file systems.


1 Answers

This doesn't work for you?

In [2]: tempfile.NamedTemporaryFile(suffix='.tif').name Out[2]: '/var/folders/gq/swc6jtld5853skyq_xc2lpc40000gn/T/tmplrtwvxg7.tif' 
like image 177
Wayne Werner Avatar answered Oct 16 '22 12:10

Wayne Werner