Temporary Files#

import tempfile
import json

Temporary Files#

Quick Start#

The following code creates a temporary file and writes some data to it.

The default file mode is "w+b". So, you should write bytes in the following example.

# Create a temporary file
tmp_file = tempfile.TemporaryFile()

# Write some data
# You should write bytes since the file mode is "w+b"
tmp_file.write(b"Hello, World!")
13

If you want to check the content of the temporary file, you can use the read() method.

But before that, remember to seek to the beginning of the file! This is because the file pointer is now at the end of the data you have written to it.

tmp_file.seek(0)
content = tmp_file.read()

print(f"file content: {content}")
file content: b'Hello, World!'

When you close the file, it will be automatically deleted.

# Close the file to delete it
tmp_file.close()

# The file is now deleted

Temporary Files with NamedTemporaryFile#

If you want to know where the temporary file is created, you may create it with NamedTemporaryFile() and then check the name property.

I have not yet figured out how to get the file path of the temporary file created by tempfile.TemporaryFile().

# Create a temporary file
tmp_file = tempfile.NamedTemporaryFile()

# This shows the path of the file
print(tmp_file.name)

# Close to delete the file
tmp_file.close()
/var/folders/ys/b1hv6dln0t38g92zzgh9xgsw0000gn/T/tmp7icnsi85

Specifying File Extensions#

# Create a temporary file
tmp_file = tempfile.NamedTemporaryFile(suffix=".json")

# This is a JSON file
print(f"file path: {tmp_file.name}")

# Write some data
tmp_file.write(b'{"message": "Hello, World!"}')

# Read and parse the data
tmp_file.seek(0)
content = tmp_file.read()
data = json.loads(content)
print(f"data: {data}")

# Close to delete the file
tmp_file.close()
file path: /var/folders/ys/b1hv6dln0t38g92zzgh9xgsw0000gn/T/tmpd2vpqs8h.json
data: {'message': 'Hello, World!'}

Context Manager#

Use a context manager to automatically close the temporary file.

with tempfile.TemporaryFile() as f:

    f.write(b"Hello, World!")

# The file is now deleted since the context manager closes it

Temporary Directories#

You can also create a temporary directory. The benefit of this is that you essentially create a temporary workspace.

# Create a temporary directory
tmp_dir = tempfile.TemporaryDirectory()

# Print the path of the temporary directory
print(f"directory path: {tmp_dir.name}")

# Delete the directory and all of its contents
tmp_dir.cleanup()
directory path: /var/folders/ys/b1hv6dln0t38g92zzgh9xgsw0000gn/T/tmpgx3trpep