The tempfile module in Python provides a way to create temporary files and directories. One of the functions provided by this module is NamedTemporaryFile, which creates a temporary file with a unique name and opens it in write mode. This function returns a file object with all the regular methods of a file object.
Example 1: The following code snippet creates a named temporary file and writes some data into it. The file is automatically deleted when it is closed.
import tempfile
with tempfile.NamedTemporaryFile(mode='w', delete=True) as temp: temp.write('Some data') temp.flush() print(temp.name)
Output: /tmp/tmpvigo3i7g
Example 2: In this example, we use NamedTemporaryFile to create a temporary file for storing a downloaded file. We first download the file using the requests package and write its content to the temporary file.
with requests.get(url) as response, tempfile.NamedTemporaryFile(delete=False) as temp: temp.write(response.content) print(f'Downloaded file saved at {temp.name}')
Output: Downloaded file saved at /var/folders/6v/w2jvnjqx6dd2fsk5xr5vzrs80000gn/T/tmp4rv67uqq
Package Library: tempfile is a core python module that provides temporary file and directory support.
Python NamedTemporaryFile.write - 60 examples found. These are the top rated real world Python examples of tempfile.NamedTemporaryFile.write extracted from open source projects. You can rate examples to help us improve the quality of examples.