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.
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.
NamedTemporaryFile
in a with-statement to create the new temporary file. We can refer it as "t."byte
literals to the file, each with a terminating newline—so the file has 3 lines of text.delete_on_close
" as false, it is not deleted automatically here.readline()
inside a while-True
loop to read all the lines in the file.strip()
to remove leading and trailing newlines from the line, and then print it to the console.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
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.