![]() |
VOOZH | about |
Tempfile is a Python module used in a situation, where we need to read multiple files, change or access the data in the file, and gives output files based on the result of processed data. Each of the output files produced during the program execution was no longer needed after the program was done. In this case, a problem arose that many output files were created and this cluttered the file system with unwanted files that would require deleting every time the program ran.
In this situation, tempfiles are used to create temporary files so that next time we don't have to find delete when our program is done with them
A temporary file can also be used for securing sensitive data. This module contains many functions to create temporary files and folders, and access them easily.
Suppose your application needs a temporary file for use within the program, i.e. it will create one file, use it to store some data, and then delete it after use. To achieve this, we can use the TemporaryFile() function.
Code:
Output:
temp: <_io.BufferedRandom name=6> temp.name: 6
Similar to reading or writing from a file, we can use the same kind of function calls to do this from a temporary file too!!
Example 1:
Output:
b'Hello world!'
Example 2:
Output:
b'Welcome to geeksforgeeks'
If your application spans multiple processes, or even hosts, naming the file is the simplest way to pass it between parts of the application. The NamedTemporaryFile() function creates a file with a name, accessed from the name attribute.
Example 1:
Output:
Creating a named temporary file.. Created file is: <tempfile._TemporaryFileWrapper object at 0x7ff135ed1710> Name of the file is: /tmp/tmpg8efl258
Example 2:
Output:
/tmp/tmp6nxmoagy
Sometimes we need to add a prefix or suffix to a temp-file's name. It will help us to identify all temp files created by our program
Example 1:
Output:
Created file is: <tempfile._TemporaryFileWrapper object at 0x7fbf5d39b6d8> Name of the file is: /tmp/demoPrefix_t_inxb7v_demoSuffix
Example 2:
Output:
/tmp/forgreeks_4sigabye_greeks