Using revised tempfile module

E

Edward C. Jones

#! /usr/bin/env python

import os, tempfile

# I have written code like this several times. It uses the deprecated
# function tempfile.mktemp. How do I write this with the new tempfile
# functions?

def do_something(filename1, filename2):
os.system('cat %s > %s' % (filename1, filename2))

filename1 = tempfile.mktemp()
filename2 = tempfile.mktemp()
try:
f = file(filename1, 'w')
f.write('abcd')
f.close()
do_something(filename1, filename2)
g = file(filename2, 'r')
print g.read()
g.close()
finally:
if os.path.exists(filename1):
os.remove(filename1)
if os.path.exists(filename2):
os.remove(filename2)
 
J

John J. Lee

Edward C. Jones said:
#! /usr/bin/env python

import os, tempfile

# I have written code like this several times. It uses the deprecated
# function tempfile.mktemp. How do I write this with the new tempfile
# functions?

You read the tempfile.mkstemp documentation.


John
 
P

Peter Hansen

John J. Lee said:
You read the tempfile.mkstemp documentation.

Or even just re-read the tempfile.mktemp documentation again, which says

Deprecated since release 2.3. Use mkstemp() instead.
Warning: Use of this function may introduce a security hole in your program.
By the time you get around to doing anything with the file name it returns,
someone else may have beaten you to the punch.

-Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,767
Messages
2,569,570
Members
45,045
Latest member
DRCM

Latest Threads

Top