In this tutorial, we will introduce the way to create a temporary file in python, temporary file will be deleted if you close it.
1. Import library
from tempfile import NamedTemporaryFile
2. Create a temporary file
f = NamedTemporaryFile('w+t')
4. Write text to temporary file
f.write('This is a temporary file.')
5. Get the temporary file name
print(f.name)
6. Read data from temporary file
# Go to the top of the file f.seek(0) # Read the file data = f.read() print(data)
7. Close temporary file, it will be deleted
f.close()