Temporary Files And Directories in Python

Python provides several ways to work with temporary files and directories. The tempfile module offers functions to create temporary files and directories that are automatically cleaned up by the operating system.

import tempfile
import os

def main():
    # The easiest way to create a temporary file is by using
    # tempfile.NamedTemporaryFile(). It creates a file and
    # opens it for reading and writing.
    with tempfile.NamedTemporaryFile(prefix="sample", delete=False) as f:
        print("Temp file name:", f.name)

        # We can write some data to the file.
        f.write(bytes([1, 2, 3, 4]))

    # The file is automatically closed when we exit the 'with' block.
    # We need to manually remove it as we set delete=False
    os.unlink(f.name)

    # If we intend to create many temporary files, we may
    # prefer to create a temporary directory.
    # tempfile.mkdtemp() returns a directory name.
    with tempfile.TemporaryDirectory(prefix="sampledir") as dname:
        print("Temp dir name:", dname)

        # Now we can create files inside this temporary directory
        fname = os.path.join(dname, "file1")
        with open(fname, 'wb') as f:
            f.write(bytes([1, 2]))

    # The temporary directory and its contents are automatically
    # removed when we exit the 'with' block.

if __name__ == "__main__":
    main()

This Python script demonstrates how to work with temporary files and directories:

  1. We use tempfile.NamedTemporaryFile() to create a temporary file. The prefix parameter allows us to specify a prefix for the filename. We set delete=False so that we can close the file and still access it by name.

  2. We write some data to the file using the write() method.

  3. After we’re done with the file, we manually remove it using os.unlink().

  4. To create a temporary directory, we use tempfile.TemporaryDirectory(). This returns a context manager that automatically removes the directory and its contents when we exit the with block.

  5. We can create files inside this temporary directory using standard file operations.

When you run this script, you’ll see output similar to:

Temp file name: /tmp/samplexxxxxxxx
Temp dir name: /tmp/sampledirxxxxxxxx

The exact names will vary as they are generated randomly to ensure uniqueness.

Python’s tempfile module handles the creation and cleanup of temporary files and directories, making it easier to work with temporary data without polluting the file system.