The tempfile Module

The tempfile module in Example 2-6 allows you to quickly come up with unique names to use for temporary files.

Example 2-6. Using the tempfile Module to Create Filenames for Temporary Files


import tempfile
import os

tempfile = tempfile.mktemp()

print "tempfile", "=>", tempfile

file = open(tempfile, "w+b")
file.write("*" * 1000)
print len(, "bytes"

 # must remove file when done
except OSError:

tempfile => C:TEMP~160-1
1000 bytes

The TemporaryFile function picks a suitable name and opens the file, as shown in Example 2-7. It also makes sure that the file is removed when it's closed. (On Unix, you can remove an open file and have it disappear when the file is closed. On other platforms, this is done via a special wrapper class.)

Example 2-7. Using the tempfile Module to Open Temporary Files


import tempfile

file = tempfile.TemporaryFile()

for i in range(100):
 file.write("*" * 100)

file.close() # removes the file!

Core Modules

More Standard Modules

Threads and Processes

Data Representation

File Formats

Mail and News Message Processing

Network Protocols


Multimedia Modules

Data Storage

Tools and Utilities

Platform-Specific Modules

Implementation Support Modules

Other Modules

Python Standard Library
Python Standard Library (Nutshell Handbooks) with
ISBN: 0596000960
EAN: 2147483647
Year: 2000
Pages: 252
Authors: Fredrik Lundh © 2008-2020.
If you may any questions please contact us: