Python's tempfile module provides an easy way to create temporary files and directories. One of the most useful functions is NamedTemporaryFile() which creates a file that has a random unique name, with an option to delete the file automatically when it is closed.
Here are some code examples:
Example 1:
import tempfile
with tempfile.NamedTemporaryFile() as file: print(f"Temporary file created: {file.name}") # do something with the file
# file is closed and deleted automatically
This code creates a temporary file with a unique name and automatically deletes it when the 'with' block exits. The file is opened in binary (default) mode.
Example 2:
import tempfile
with tempfile.NamedTemporaryFile(mode='w', delete=False) as file: file.write("Hello, world!\n") print(f"Temporary file created: {file.name}")
# file is not deleted
In this example, a temporary file is created with 'w' (write) mode and the option to not delete the file is specified. The file is opened in text mode, so we can write strings to it. The file is not deleted, so it can be reused later or examined manually.
These examples use the 'tempfile' package library, which is part of Python's standard library.
Python NamedTemporaryFile - 60 examples found. These are the top rated real world Python examples of tempfile.NamedTemporaryFile extracted from open source projects. You can rate examples to help us improve the quality of examples.