Title: Create A Temporary File
Slug: create_a_temporary_file
Summary: Create A Temporary File Using Python.
Date: 2017-02-02 12:00
Category: Python
Tags: Basics
Authors: Chris Albon

Preliminaries


In [1]:
from tempfile import NamedTemporaryFile

Create A Temporary File


In [2]:
f = NamedTemporaryFile('w+t')

Write To The Temp File


In [3]:
# Write to the file, the output is the number of characters
f.write('Nobody lived on Deadweather but us and the pirates. It wasn’t hard to understand why.')


Out[3]:
85

View The Tmp File's Name


In [4]:
f.name


Out[4]:
'/var/folders/0b/pj3wsd750fjf8xzfb0n127w80000gn/T/tmphv1dkovx'

Read The File


In [5]:
# Go to the top of the file
f.seek(0)

# Read the file
f.read()


Out[5]:
'Nobody lived on Deadweather but us and the pirates. It wasn’t hard to understand why.'

Close (And Thus Delete) The File


In [6]:
f.close()