
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create Unique Temporary File Name Using Python
Temporary files are created to store data temporarily during the execution of a program or while working with large amount of data. To create a temporary file we can use the tempfile module, as it creates unique names and stores in platform-dependent default location .
Specifically the tempfile module is used as the files created using this module are deleted as soon as they are closed.
Creating a Temporary File
A temporary file is created using the TemporaryFile() function of the tempfile module. This by default opens the file in 'w+b' mode, which allows to both read and write the opened file. Also, since the binary mode is by default it allows to work with all types of data.
Example
In the example below, we will use the TemporaryFile() function to create a temporary file:
import tempfile tf = tempfile.TemporaryFile() print(tf) print(tf)
The output returned by the above code is as follows:
#Describes the file object created
<_io.BufferedRandom name=3>
3
In the output returned, the Bufferedrandom is a class for buffered binary files that support random access. The name=3 indicates that the file object is associated to file descriptor (small, non-negative integers used by operating systems to track open files) 3.
Creating a Named Temporary File
To create a named temporary file, we use the NamedTemporaryFile() function that is similar to TemporyFile() function but with a visible name in the file system. Additionally, unlike the temporary file getting deleted by default when closed, this function has a delete parameter which can be set as FALSE to prevent the file from being deleted as soon as it is closed.
Example
In the example below, we will use the NamedTemporaryFile() to create a named temporary file:
import tempfile tf = tempfile.NamedTemporaryFile() print(tf) print(tf.name)
The output returned by the above code is as follows:
<tempfile._TemporaryFileWrapper object at 0x7f0916d3ad50>
/tmp/tmp2ituek6c
In the output returned, 0x7f0916d3ad50 is the memory address which will be different each time you run. And the /tmp/tmp2ituek6c is the actual path of the temporary file on the file system.
Adding a Suffix or Prefix When Creating a Temporary File
You can additionally add a suffix or prefix to the name of the temporary file, by specifying the additional parameters 'suffix' and 'prefix' to the NamedTemporaryFile() function , which is implemented in the below example:
import tempfile tf = tempfile.NamedTemporaryFile(prefix='pre_tp_', suffix='_suf_tp') print(tf.name)
The output returned by the above code is as follows -
/tmp/pre_tp_1hntijef_suf_tp