The Wayback Machine - https://web.archive.org/web/20240821182020/https://www.geeksforgeeks.org/python-tempfile-module/
Open In App

Python tempfile module

Last Updated : 11 Dec, 2020
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

Working with temporary files

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.

Creating Temporary Files

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.

  • First, we have to import tempfile then the file is created using the TemporaryFile() function.
  • The file is opened in w+b (both read and write to the open file)mode by default.
  • This function creates a temporary file in the temp directory and returns a file object
  • the file’s entry in the temp folder is removed as soon as the file object is closed

Code:

Python3




import tempfile
  
temp = tempfile.TemporaryFile()
print('temp:',temp)
print('temp.name:', temp.name)
temp.close()


Output:

temp: <_io.BufferedRandom name=6>
temp.name: 6

Reading and writing plain text into Temporary Files

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!!

  • Create a temporary file and write some data to it
  • After writing, you have to rewind the file handle using seek() in order to read the data back from it.
  • Go back to the beginning and read data from the file
  • Close the file, it will be removed

Example 1:

Python3




import tempfile
  
temp = tempfile.TemporaryFile()
  
try:
    temp.write(b'Hello world!')
    temp.seek(0)
  
    print(temp.read())
finally:
    temp.close()


Output:

b'Hello world!'

Example 2:

Python3




import tempfile
  
f = tempfile.TemporaryFile()
  
try:
  f.write(b'Welcome to geeksforgeeks')
  f.seek(0)
  data=f.read()
  print(data)
finally:
  f.close()


Output:

b'Welcome to geeksforgeeks'

Creating a named Temporary Files 

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.

  • First import tempfile and then the file is created using the NamedTemporaryFile() function.
  • NamedTemporaryFile returns a file-like object that can be used as temporary storage, however, contrary to TemporaryFile, a file created with NamedTemporaryFile is guaranteed to have a visible name during its lifetime.
  • TemporaryFile gets destroyed as soon as the file is closed, NamedTemporaryFile has support for the deleted flags, which defaults to True

Example 1:

Python3




import tempfile
  
print("Creating a named temporary file..")
temp = tempfile.NamedTemporaryFile()
  
print("Created file is:", temp)
print("Name of the file is:", temp.name)
temp.close()


Output:

Creating a named temporary file..
Created file is: <tempfile._TemporaryFileWrapper object at 0x7ff135ed1710>
Name of the file is: /tmp/tmpg8efl258

Example 2:

Python3




import tempfile
  
fo = tempfile.NamedTemporaryFile()
print(fo.name)
  
fo.close()


Output:

/tmp/tmp6nxmoagy

Providing Filename Suffix and Prefix

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

  • We can add suffix or prefix to the name of a named temporary file, by using the parameters ‘suffix’ and ‘prefix’.
  • Use the same NamedTemporaryFile function defined above. The only thing we need to add is two extra parameters while calling this function: suffix and prefix
  • So, if we will pass the two extra arguments suffix and prefix to the NamedTemporaryFile() function, it will automatically add those at the start and end of the file name

Example 1:

Python3




import tempfile
  
temp = tempfile.NamedTemporaryFile(prefix="demoPrefix_",
                                   suffix="_demoSuffix")
  
print("Created file is:", temp)
print("Name of the file is:", temp.name)
temp.close()


Output:

Created file is: <tempfile._TemporaryFileWrapper object at 0x7fbf5d39b6d8>
Name of the file is: /tmp/demoPrefix_t_inxb7v_demoSuffix

Example 2:

Python3




import tempfile
  
temp=tempfile.NamedTemporaryFile(suffix='_greeks',
                                 prefix='forgreeks_')
print(temp.name)


Output:

/tmp/forgreeks_4sigabye_greeks


Similar Reads

Create temporary files and directories using tempfile
Python tempfile module allows you to create a temporary file and perform various operations on it. Temporary files may be required when we need to store data temporarily during the program's execution or when we are working with a large amount of data. These files are created with unique names and stored in a platform-dependent default location. Th
5 min read
MySQL-Connector-Python module in Python
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same command. In this article, we will be disc
2 min read
twitter-text-python (ttp) module - Python
twitter-text-python is a Tweet parser and formatter for Python. Amongst many things, the tasks that can be performed by this module are : reply : The username of the handle to which the tweet is being replied to. users : All the usernames mentioned in the tweet. tags : All the hashtags mentioned in the tweet. urls : All the URLs mentioned in the tw
3 min read
Python calendar module : formatmonth() method
Calendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. class calendar.TextCalendar(firstweekday=0) can be used to generate plain text
2 min read
Python | Writing to an excel file using openpyxl module
Prerequisite : Reading an excel file using openpyxl Openpyxl is a Python library for reading and writing Excel (with extension xlsx/xlsm/xltx/xltm) files. The openpyxl module allows Python program to read and modify Excel files. For example, user might have to go through thousands of rows and pick out few handful information to make small changes b
3 min read
Stack and Queue in Python using queue Module
A simple python List can act as queue and stack as well. Queue mechanism is used widely and for many purposes in daily life. A queue follows FIFO rule(First In First Out) and is used in programming for sorting and for many more things. Python provides Class queue as a module which has to be generally created in languages such as C/C++ and Java. 1.
3 min read
PyMsgBox module in Python
PyMsgBox is simple, cross-platform, purely implemented in Python for message boxes as JavaScript has. It uses Python's built-in Tkinter module for its GUI. Installation This module does not built-in Python. To install it type the below command in the terminal. pip install PyMsgBox There are four functions in PyMsgBox, which follow JavaScript’s mess
2 min read
uniform() method in Python Random module
uniform() is a method specified in the random library in Python 3. Nowadays, in general, day-day tasks, there's always the need to generate random numbers in a range. Normal programming constructs require a method more than just one word to achieve this particular task. In python, there's an inbuilt method, "uniform()" which performs this task with
2 min read
mode() function in Python statistics module
The mode of a set of data values is the value that appears most often. It is the value at which the data is most likely to be sampled. A mode of a continuous probability distribution is often considered to be any value x at which its probability density function has a local maximum value, so any peak is a mode.Python is very robust when it comes to
5 min read
median_low() function in Python statistics module
Median is often referred to as the robust measure of the central location and is less affected by the presence of outliers in data. statistics module in Python allows three options to deal with median / middle elements in a data set, which are median(), median_low() and median_high(). The low median is always a member of the data set. When the numb
4 min read
median_high() function in Python statistics module
Median is often referred to as the robust measure of the central location and is less affected by the presence of outliers in data. statistics module in Python allows three options to deal with median / middle elements in a data set, which are median(), median_low() and median_high(). The high median is always a member of the data set. When the num
4 min read
median_grouped() function in Python statistics module
Coming to Statistical functions, median of a data-set is the measure of robust central tendency, which is less affected by the presence of outliers in data. As seen previously, medians of an ungrouped data-set using median(), median_high(), median_low() functions. Python gives the option to calculate the median of grouped and continuous data functi
4 min read
stdev() method in Python statistics module
Statistics module in Python provides a function known as stdev() , which can be used to calculate the standard deviation. stdev() function only calculates standard deviation from a sample of data, rather than an entire population. To calculate standard deviation of an entire population, another function known as pstdev() is used. Standard Deviation
5 min read
Plotting graphs using Python's plotly and cufflinks module
plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. cufflink connects plotly with pandas to create g
2 min read
Python | ASCII art using pyfiglet module
pyfiglet takes ASCII text and renders it in ASCII art fonts. figlet_format method convert ASCII text into ASCII art fonts. It takes following arguments : text font ( DEFAULT_FONT = 'standard' ) Command to install pyfiglet module : pip install pyfiglet Code #1: Text in default font # import pyfiglet module import pyfiglet result = pyfiglet.figlet_fo
6 min read
easyinput module in Python
easyinput module in Python offers an easy input interface analogous to cin stream in C++. It supports multiple data types including files and provides functionalities such as input till different data types, multi-line input, etc. Installation To install this module type the below command in the terminal. pip install easyinputFunction Usedread(*typ
3 min read
Python | Adjusting rows and columns of an excel file using openpyxl module
Prerequisites : Excel file using openpyxl writing | reading Set the height and width of the cells:Worksheet objects have row_dimensions and column_dimensions attributes that control row heights and column widths. A sheet’s row_dimensions and column_dimensions are dictionary-like values; row_dimensions contains RowDimension objects and column_dimens
3 min read
Python | Plotting charts in excel sheet using openpyxl module | Set - 1
Prerequisite: Reading &amp; Writing to excel sheet using openpyxl Openpyxl is a Python library using which one can perform multiple operations on excel files like reading, writing, arithmetic operations and plotting graphs. Let's see how to plot different charts using realtime data. Charts are composed of at least one series of one or more data poi
6 min read
Python | Plotting charts in excel sheet using openpyxl module | Set – 2
Prerequisite: Python | Plotting charts in excel sheet using openpyxl module | Set – 1 Openpyxl is a Python library using which one can perform multiple operations on excel files like reading, writing, arithmetic operations and plotting graphs. Charts are composed of at least one series of one or more data points. Series themselves are comprised of
6 min read
Python | Plotting charts in excel sheet using openpyxl module | Set 3
Prerequisite : Plotting charts in excel sheet using openpyxl module Set - 1 | Set – 2Openpyxl is a Python library using which one can perform multiple operations on excel files like reading, writing, arithmetic operations and plotting graphs. Charts are composed of at least one series of one or more data points. Series themselves are comprised of r
7 min read
Python | Create and write on excel file using xlsxwriter module
XlsxWriter is a Python module for writing files in the XLSX file format. It can be used to write text, numbers, and formulas to multiple worksheets. Also, it supports features such as formatting, images, charts, page setup, auto filters, conditional formatting and many others.Use this command to install xlsxwriter module: pip install xlsxwriter Not
3 min read
spwd module in Python
spwd module in Python provides access to the Unix shadow password database. The entries stored in the database is tuple-like objects whose attributes are similar as the members of spwd structure defined in &lt;shadow.h&gt; header file. Following are the attributes of tuple-like object which represents the entries stored in Unix shadow password data
5 min read
Pygorithm module in Python
Pygorithm module is a Python module written purely in Python and for educational purposes only. One can get the code, time complexities and much more by just importing the required algorithm. It is a good way to start learning Python programming and understanding concepts. Pygorithm module can also help to learn the implementation of all major algo
2 min read
Python | Plotting Area charts in excel sheet using XlsxWriter module
Prerequisite: Create and write on an excel file XlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot different charts using realtime data. Charts are composed of at least one series of one or more data points. Series the
6 min read
Python | Getting started with SymPy module
SymPy is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) while keeping the code as simple as possible in order to be comprehensible and easily extensible. SymPy is written entirely in Python. SymPy only depends on mpmath, a pure Python library for arbitrary floating point arithmetic, making
4 min read
Python | Plotting bar charts in excel sheet using XlsxWriter module
Prerequisite: Create and Write on an excel file.XlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot different type of Bar charts using realtime data. Charts are composed of at least one series of one or more data points
6 min read
Python | Plotting Radar charts in excel sheet using XlsxWriter module
Prerequisite:Create and Write on excel file XlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot different type of Radar charts using realtime data. Charts are composed of at least one series of one or more data points.
6 min read
Python | Plotting scatter charts in excel sheet using XlsxWriter module
Prerequisite: Create and Write on an excel file. XlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot different type of Scatter charts using realtime data. Charts are composed of at least one series of one or more data p
10 min read
Python | Plotting column charts in excel sheet using XlsxWriter module
Prerequisite: Create and Write on an excel file.XlsxWriter is a Python library using which one can perform multiple operations on excel files like creating, writing, arithmetic operations and plotting graphs. Let’s see how to plot different type of Column charts using realtime data. Charts are composed of at least one series of one or more data poi
7 min read
Python calendar module | itermonthdays2() method
Calendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. itermonthdays2() method is used to get an iterator for the month in the year s
2 min read
three90RightbarBannerImg