Home
Python
tempfile Example
Updated Mar 6, 2024
Dot Net Perls
Tempfile. Sometimes a Python program may need to create a temporary file to write to and then read from. The file is not needed after the program ends, and can be deleted.
It would be possible to write this logic in Python. But often files might be left after the program stops working. With tempfile, a module, we can approach this problem more reliably.
Example. This Python program creates a temporary file, and then writes some text lines to it. It then reads in that same file and reads from it.
Step 1 We call NamedTemporaryFile in a with-statement to create the new temporary file. We can refer it as "t."
Step 2 We write 3 byte literals to the file, each with a terminating newline—so the file has 3 lines of text.
Step 3 We close the temporary file, and because we specified "delete_on_close" as false, it is not deleted automatically here.
Step 4 We open the temporary file by its "name" property using the standard Python open built-in function.
File
Step 5 We call readline() inside a while-True loop to read all the lines in the file.
readline
Step 6 We call strip() to remove leading and trailing newlines from the line, and then print it to the console.
String strip
print
import tempfile # Step 1: create new temporary file, and do not delete on close. with tempfile.NamedTemporaryFile(delete_on_close=False) as t: # Step 2: write some lines. t.write(b"bird\n") t.write(b"frog\n") t.write(b"dog\n") # Step 3: close the temporary file. t.close() # Step 4: open the temporary file by name. with open(t.name, "r") as f: # Step 5: read lines until no line is returned. while True: line = f.readline() if line == "": break # Step 6: strip the line and print it. stripped = line.strip() print("LINE =", stripped)
LINE = bird LINE = frog LINE = dog
Summary. By using tempfile, we can automatically clean up any temporary files we create. We can use NamedTemporaryFile to read a temporary file after creating it.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Mar 6, 2024 (new).
Home
Changes
© 2007-2025 Sam Allen