Home
Map
tempfile ExampleUse the tempfile module and the NamedTemporaryFile method to create, write to, and read from a temporary file.
Python
This page was last reviewed on Mar 6, 2024.
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Mar 6, 2024 (new).
Home
Changes
© 2007-2024 Sam Allen.