from tempfile import TemporaryFilewithTemporaryFile('w+t')as f:# Read/write to the file f.write('Hello World\n') f.write('Testing\n')# Seek back to beginning and read the data f.seek(0) data = f.read()# Temporary file is destroyed
with TemporaryFile('w+t', encoding='utf-8', errors='ignore') as f:
...
from tempfile import NamedTemporaryFile
with NamedTemporaryFile('w+t') as f:
print('filename is:', f.name)
...
# File automatically destroyed
with NamedTemporaryFile('w+t', delete=False) as f:
print('filename is:', f.name)
...
from tempfile import TemporaryDirectory
with TemporaryDirectory() as dirname:
print('dirname is:', dirname)
# Use the directory
...
# Directory and all contents destroyed