Massive changes from SF 589982 (tempfile.py rewrite, by Zack
Weinberg).  This changes all uses of deprecated tempfile functions to
the recommended ones.
diff --git a/Demo/pdist/rcslib.py b/Demo/pdist/rcslib.py
index 6d2e313..4e72766 100755
--- a/Demo/pdist/rcslib.py
+++ b/Demo/pdist/rcslib.py
@@ -143,22 +143,17 @@
         if message and message[-1] != '\n':
             message = message + '\n'
         lockflag = "-u"
-        textfile = None
-        try:
-            if new:
-                textfile = tempfile.mktemp()
-                f = open(textfile, 'w')
-                f.write(message)
-                f.close()
-                cmd = 'ci %s%s -t%s %s %s' % \
-                      (lockflag, rev, textfile, otherflags, name)
-            else:
-                message = regsub.gsub('\([\\"$`]\)', '\\\\\\1', message)
-                cmd = 'ci %s%s -m"%s" %s %s' % \
-                      (lockflag, rev, message, otherflags, name)
-            return self._system(cmd)
-        finally:
-            if textfile: self._remove(textfile)
+        if new:
+            f = tempfile.NamedTemporaryFile()
+            f.write(message)
+            f.flush()
+            cmd = 'ci %s%s -t%s %s %s' % \
+                  (lockflag, rev, f.name, otherflags, name)
+        else:
+            message = regsub.gsub('\([\\"$`]\)', '\\\\\\1', message)
+            cmd = 'ci %s%s -m"%s" %s %s' % \
+                  (lockflag, rev, message, otherflags, name)
+        return self._system(cmd)
 
     # --- Exported support methods ---
 
diff --git a/Demo/pdist/rcvs.py b/Demo/pdist/rcvs.py
index 9129c28..24036c7 100755
--- a/Demo/pdist/rcvs.py
+++ b/Demo/pdist/rcvs.py
@@ -172,17 +172,13 @@
 		if self.lsum == sum:
 			return
 		import tempfile
-		tfn = tempfile.mktemp()
-		try:
-			tf = open(tfn, 'w')
-			tf.write(data)
-			tf.close()
-			print 'diff %s -r%s %s' % (flags, rev, fn)
-			sts = os.system('diff %s %s %s' % (flags, tfn, fn))
-			if sts:
-				print '='*70
-		finally:
-			remove(tfn)
+		tf = tempfile.NamedTemporaryFile()
+		tf.write(data)
+		tf.flush()
+		print 'diff %s -r%s %s' % (flags, rev, fn)
+		sts = os.system('diff %s %s %s' % (flags, tf.name, fn))
+		if sts:
+			print '='*70
 
 	def commitcheck(self):
 		return self.action() != 'C'
diff --git a/Demo/pdist/rrcs.py b/Demo/pdist/rrcs.py
index ecb01a2..a07260c 100755
--- a/Demo/pdist/rrcs.py
+++ b/Demo/pdist/rrcs.py
@@ -102,17 +102,13 @@
 		flags = flags + ' ' + o + a
 	flags = flags[1:]
 	data = x.get(fn)
-	tfn = tempfile.mktemp()
-	try:
-		tf = open(tfn, 'w')
-		tf.write(data)
-		tf.close()
-		print 'diff %s -r%s %s' % (flags, x.head(fn), fn)
-		sts = os.system('diff %s %s %s' % (flags, tfn, fn))
-		if sts:
-			print '='*70
-	finally:
-		remove(tfn)
+	tf = tempfile.NamedTemporaryFile()
+	tf.write(data)
+	tf.flush()
+	print 'diff %s -r%s %s' % (flags, x.head(fn), fn)
+	sts = os.system('diff %s %s %s' % (flags, tf.name, fn))
+	if sts:
+		print '='*70
 
 def same(x, copts, fn, data = None):
 	if data is None:
diff --git a/Demo/scripts/pp.py b/Demo/scripts/pp.py
index 2496046..64e57ee 100755
--- a/Demo/scripts/pp.py
+++ b/Demo/scripts/pp.py
@@ -120,19 +120,11 @@
 program = program + (string.joinfields(epilogue, '\n') + '\n')
 
 import tempfile
-tfn = tempfile.mktemp()
-try:
-	fp = open(tfn, 'w')
-	fp.write(program)
-	fp.close()
-	if DFLAG:
-		import pdb
-		pdb.run('execfile(' + `tfn` + ')')
-	else:
-		execfile(tfn)
-finally:
-	import os
-	try:
-		os.unlink(tfn)
-	except:
-		pass
+fp = tempfile.NamedTemporaryFile()
+fp.write(program)
+fp.flush()
+if DFLAG:
+	import pdb
+	pdb.run('execfile(' + `tfn` + ')')
+else:
+	execfile(tfn)
diff --git a/Lib/cgitb.py b/Lib/cgitb.py
index b39fd93..2602d57 100644
--- a/Lib/cgitb.py
+++ b/Lib/cgitb.py
@@ -193,10 +193,10 @@
 
         if self.logdir is not None:
             import os, tempfile
-            name = tempfile.mktemp(['.html', '.txt'][text])
-            path = os.path.join(self.logdir, os.path.basename(name))
+            (fd, name) = tempfile.mkstemp(suffix=['.html', '.txt'][text],
+                                          dir=self.logdir)
             try:
-                file = open(path, 'w')
+                file = os.fdopen(fd, 'w')
                 file.write(doc)
                 file.close()
                 msg = '<p> %s contains the description of this error.' % path
diff --git a/Lib/distutils/command/bdist_wininst.py b/Lib/distutils/command/bdist_wininst.py
index 71e51bf..b538319 100644
--- a/Lib/distutils/command/bdist_wininst.py
+++ b/Lib/distutils/command/bdist_wininst.py
@@ -130,8 +130,9 @@
 
         # And make an archive relative to the root of the
         # pseudo-installation tree.
-        from tempfile import mktemp
-        archive_basename = mktemp()
+        from tempfile import NamedTemporaryFile
+        arc = NamedTemporaryFile(".zip")
+        archive_basename = arc.name[:-4]
         fullname = self.distribution.get_fullname()
         arcname = self.make_archive(archive_basename, "zip",
                                     root_dir=self.bdist_dir)
@@ -139,7 +140,7 @@
         self.create_exe(arcname, fullname, self.bitmap)
         # remove the zip-file again
         log.debug("removing temporary file '%s'", arcname)
-        os.remove(arcname)
+        arc.close()
 
         if not self.keep_temp:
             remove_tree(self.bdist_dir, dry_run=self.dry_run)
diff --git a/Lib/distutils/util.py b/Lib/distutils/util.py
index 23c29eb..d9c6224 100644
--- a/Lib/distutils/util.py
+++ b/Lib/distutils/util.py
@@ -359,11 +359,11 @@
     # "Indirect" byte-compilation: write a temporary script and then
     # run it with the appropriate flags.
     if not direct:
-        from tempfile import mktemp
-        script_name = mktemp(".py")
+        from tempfile import mkstemp
+        (script_fd, script_name) = mkstemp(".py")
         log.info("writing byte-compilation script '%s'", script_name)
         if not dry_run:
-            script = open(script_name, "w")
+            script = os.fdopen(script_fd, "w")
 
             script.write("""\
 from distutils.util import byte_compile
diff --git a/Lib/hotshot/stones.py b/Lib/hotshot/stones.py
index 5a029d5..e171fbc 100644
--- a/Lib/hotshot/stones.py
+++ b/Lib/hotshot/stones.py
@@ -8,12 +8,10 @@
 
 if sys.argv[1:]:
     logfile = sys.argv[1]
-    cleanup = 0
 else:
     import tempfile
-    logfile = tempfile.mktemp()
-    cleanup = 1
-
+    logf = tempfile.NamedTemporaryFile()
+    logfile = logf.name
 
 p = hotshot.Profile(logfile)
 benchtime, stones = p.runcall(test.pystone.pystones)
@@ -24,8 +22,6 @@
 print "This machine benchmarks at %g pystones/second" % stones
 
 stats = hotshot.stats.load(logfile)
-if cleanup:
-    os.unlink(logfile)
 stats.strip_dirs()
 stats.sort_stats('time', 'calls')
 try:
diff --git a/Lib/mimetools.py b/Lib/mimetools.py
index f97787a..f1e20d4 100644
--- a/Lib/mimetools.py
+++ b/Lib/mimetools.py
@@ -202,8 +202,8 @@
     pipe.close()
 
 def pipethrough(input, command, output):
-    tempname = tempfile.mktemp()
-    temp = open(tempname, 'w')
+    (fd, tempname) = tempfile.mkstemp()
+    temp = os.fdopen(fd, 'w')
     copyliteral(input, temp)
     temp.close()
     pipe = os.popen(command + ' <' + tempname, 'r')
diff --git a/Lib/pipes.py b/Lib/pipes.py
index b565654..9de22e1 100644
--- a/Lib/pipes.py
+++ b/Lib/pipes.py
@@ -225,7 +225,8 @@
         lkind = list[i-1][2]
         rkind = list[i][2]
         if lkind[1] == 'f' or rkind[0] == 'f':
-            temp = tempfile.mktemp()
+            (fd, temp) = tempfile.mkstemp()
+            os.close(fd)
             garbage.append(temp)
             list[i-1][-1] = list[i][0] = temp
     #
diff --git a/Lib/plat-irix5/torgb.py b/Lib/plat-irix5/torgb.py
index 7cc3b47..c9fee0d 100755
--- a/Lib/plat-irix5/torgb.py
+++ b/Lib/plat-irix5/torgb.py
@@ -70,7 +70,8 @@
 
 def _torgb(filename, temps):
 	if filename[-2:] == '.Z':
-		fname = tempfile.mktemp()
+		(fd, fname) = tempfile.mkstemp()
+		os.close(fd)
 		temps.append(fname)
 		sts = uncompress.copy(filename, fname)
 		if sts:
@@ -91,7 +92,8 @@
 	if ftype is None or not table.has_key(ftype):
 		raise error, \
 			filename + ': unsupported image file type ' + `ftype`
-	temp = tempfile.mktemp()
+	(fd, temp) = tempfile.mktemp()
+	os.close(fd)
 	sts = table[ftype].copy(fname, temp)
 	if sts:
 		raise error, filename + ': conversion to rgb failed'
diff --git a/Lib/plat-irix6/torgb.py b/Lib/plat-irix6/torgb.py
index 7cc3b47..c9fee0d 100644
--- a/Lib/plat-irix6/torgb.py
+++ b/Lib/plat-irix6/torgb.py
@@ -70,7 +70,8 @@
 
 def _torgb(filename, temps):
 	if filename[-2:] == '.Z':
-		fname = tempfile.mktemp()
+		(fd, fname) = tempfile.mkstemp()
+		os.close(fd)
 		temps.append(fname)
 		sts = uncompress.copy(filename, fname)
 		if sts:
@@ -91,7 +92,8 @@
 	if ftype is None or not table.has_key(ftype):
 		raise error, \
 			filename + ': unsupported image file type ' + `ftype`
-	temp = tempfile.mktemp()
+	(fd, temp) = tempfile.mktemp()
+	os.close(fd)
 	sts = table[ftype].copy(fname, temp)
 	if sts:
 		raise error, filename + ': conversion to rgb failed'
diff --git a/Lib/pydoc.py b/Lib/pydoc.py
index 0c46c8e..e2cd846 100755
--- a/Lib/pydoc.py
+++ b/Lib/pydoc.py
@@ -1203,8 +1203,8 @@
         return lambda text: pipepager(text, 'less')
 
     import tempfile
-    filename = tempfile.mktemp()
-    open(filename, 'w').close()
+    (fd, filename) = tempfile.mkstemp()
+    os.close(fd)
     try:
         if hasattr(os, 'system') and os.system('more %s' % filename) == 0:
             return lambda text: pipepager(text, 'more')
@@ -1229,8 +1229,8 @@
 def tempfilepager(text, cmd):
     """Page through text by invoking a program on a temporary file."""
     import tempfile
-    filename = tempfile.mktemp()
-    file = open(filename, 'w')
+    (fd, filename) = tempfile.mkstemp()
+    file = os.fdopen(fd, 'w')
     file.write(text)
     file.close()
     try:
diff --git a/Lib/test/pickletester.py b/Lib/test/pickletester.py
index 870a8d6..eb97a9c 100644
--- a/Lib/test/pickletester.py
+++ b/Lib/test/pickletester.py
@@ -1,5 +1,5 @@
 import unittest
-from test.test_support import TestFailed, have_unicode
+from test.test_support import TestFailed, have_unicode, TESTFN
 
 class C:
     def __cmp__(self, other):
@@ -269,17 +269,19 @@
 class AbstractPickleModuleTests(unittest.TestCase):
 
     def test_dump_closed_file(self):
-        import tempfile, os
-        fn = tempfile.mktemp()
-        f = open(fn, "w")
-        f.close()
-        self.assertRaises(ValueError, self.module.dump, 123, f)
-        os.remove(fn)
+        import os
+        f = open(TESTFN, "w")
+        try:
+            f.close()
+            self.assertRaises(ValueError, self.module.dump, 123, f)
+        finally:
+            os.remove(TESTFN)
 
     def test_load_closed_file(self):
-        import tempfile, os
-        fn = tempfile.mktemp()
-        f = open(fn, "w")
-        f.close()
-        self.assertRaises(ValueError, self.module.dump, 123, f)
-        os.remove(fn)
+        import os
+        f = open(TESTFN, "w")
+        try:
+            f.close()
+            self.assertRaises(ValueError, self.module.dump, 123, f)
+        finally:
+            os.remove(TESTFN)
diff --git a/Lib/test/test_anydbm.py b/Lib/test/test_anydbm.py
index 54d2783..0cdc2c3 100644
--- a/Lib/test/test_anydbm.py
+++ b/Lib/test/test_anydbm.py
@@ -6,11 +6,10 @@
 import os
 import unittest
 import anydbm
-import tempfile
 import glob
 from test import test_support
 
-_fname = tempfile.mktemp()
+_fname = test_support.TESTFN
 
 def _delete_files():
     # we don't know the precise name the underlying database uses
diff --git a/Lib/test/test_binhex.py b/Lib/test/test_binhex.py
index 2de35ce..2f89703 100755
--- a/Lib/test/test_binhex.py
+++ b/Lib/test/test_binhex.py
@@ -6,7 +6,6 @@
 """
 import binhex
 import os
-import tempfile
 import unittest
 from test import test_support
 
@@ -14,8 +13,8 @@
 class BinHexTestCase(unittest.TestCase):
 
     def setUp(self):
-        self.fname1 = tempfile.mktemp()
-        self.fname2 = tempfile.mktemp()
+        self.fname1 = test_support.TESTFN + "1"
+        self.fname2 = test_support.TESTFN + "2"
 
     def tearDown(self):
         try: os.unlink(self.fname1)
diff --git a/Lib/test/test_bsddb.py b/Lib/test/test_bsddb.py
index 5cd3958..aa58ef8 100755
--- a/Lib/test/test_bsddb.py
+++ b/Lib/test/test_bsddb.py
@@ -5,8 +5,7 @@
 import os
 import bsddb
 import dbhash # Just so we know it's imported
-import tempfile
-from test.test_support import verbose, verify
+from test.test_support import verbose, verify, TESTFN
 
 def test(openmethod, what, ondisk=1):
 
@@ -14,7 +13,7 @@
         print '\nTesting: ', what, (ondisk and "on disk" or "in memory")
 
     if ondisk:
-        fname = tempfile.mktemp()
+        fname = TESTFN
     else:
         fname = None
     f = openmethod(fname, 'c')
diff --git a/Lib/test/test_commands.py b/Lib/test/test_commands.py
index 5ea08bc..56d4e7c 100644
--- a/Lib/test/test_commands.py
+++ b/Lib/test/test_commands.py
@@ -24,10 +24,17 @@
         self.assertEquals(getoutput('echo xyzzy'), 'xyzzy')
         self.assertEquals(getstatusoutput('echo xyzzy'), (0, 'xyzzy'))
 
-        # we use mktemp in the next line to get a filename which we
-        # _know_ won't exist.  This is guaranteed to fail.
-        status, output = getstatusoutput('cat ' + tempfile.mktemp())
-        self.assertNotEquals(status, 0)
+        # we use mkdtemp in the next line to create an empty directory
+        # under our exclusive control; from that, we can invent a pathname
+        # that we _know_ won't exist.  This is guaranteed to fail.
+        try:
+            dir = tempfile.mkdtemp()
+            name = os.path.join(dir, "foo")
+
+            status, output = getstatusoutput('cat ' + name)
+            self.assertNotEquals(status, 0)
+        finally:
+            os.rmdir(dir)
 
     def test_getstatus(self):
         # This pattern should match 'ls -ld /.' on any posix
diff --git a/Lib/test/test_dumbdbm.py b/Lib/test/test_dumbdbm.py
index 7417f12..4d1bc0e 100644
--- a/Lib/test/test_dumbdbm.py
+++ b/Lib/test/test_dumbdbm.py
@@ -6,10 +6,9 @@
 import os
 import unittest
 import dumbdbm
-import tempfile
 from test import test_support
 
-_fname = tempfile.mktemp()
+_fname = test_support.TESTFN
 
 def _delete_files():
     for ext in [".dir", ".dat", ".bak"]:
diff --git a/Lib/test/test_gzip.py b/Lib/test/test_gzip.py
index 9156d9e..bb4ed49 100644
--- a/Lib/test/test_gzip.py
+++ b/Lib/test/test_gzip.py
@@ -1,8 +1,8 @@
-from test.test_support import verify
+from test.test_support import verify, TESTFN
 import sys, os
-import gzip, tempfile
+import gzip
 
-filename = tempfile.mktemp()
+filename = TESTFN
 
 data1 = """  int length=DEFAULTALLOC, err = Z_OK;
   PyObject *RetVal;
diff --git a/Lib/test/test_netrc.py b/Lib/test/test_netrc.py
index 034b105..15e7e68 100644
--- a/Lib/test/test_netrc.py
+++ b/Lib/test/test_netrc.py
@@ -1,5 +1,5 @@
 
-import netrc, os, tempfile, unittest
+import netrc, os, unittest
 from test import test_support
 
 TEST_NETRC = """
@@ -17,7 +17,7 @@
 
 """
 
-temp_filename = tempfile.mktemp()
+temp_filename = test_support.TESTFN
 
 class NetrcTestCase(unittest.TestCase):
 
diff --git a/Lib/test/test_pkg.py b/Lib/test/test_pkg.py
index 224cefa..7dec2e9 100644
--- a/Lib/test/test_pkg.py
+++ b/Lib/test/test_pkg.py
@@ -8,7 +8,8 @@
 # Helpers to create and destroy hierarchies.
 
 def mkhier(root, descr):
-    mkdir(root)
+    if not os.path.isdir(root):
+        mkdir(root)
     for name, contents in descr:
         comps = name.split()
         fullname = root
@@ -52,18 +53,17 @@
 # Helper to run a test
 
 def runtest(hier, code):
-    root = tempfile.mktemp()
+    root = tempfile.mkdtemp()
     mkhier(root, hier)
     savepath = sys.path[:]
-    codefile = tempfile.mktemp()
-    f = open(codefile, "w")
-    f.write(code)
-    f.close()
+    codefile = tempfile.NamedTemporaryFile()
+    codefile.write(code)
+    codefile.flush()
     try:
         sys.path.insert(0, root)
         if verbose: print "sys.path =", sys.path
         try:
-            execfile(codefile, globals(), {})
+            execfile(codefile.name, globals(), {})
         except:
             traceback.print_exc(file=sys.stdout)
     finally:
@@ -72,7 +72,6 @@
             cleanout(root)
         except (os.error, IOError):
             pass
-        os.remove(codefile)
 
 # Test descriptions
 
diff --git a/Lib/test/test_pkgimport.py b/Lib/test/test_pkgimport.py
index 523ba5a..1343173 100644
--- a/Lib/test/test_pkgimport.py
+++ b/Lib/test/test_pkgimport.py
@@ -17,8 +17,7 @@
                 del sys.modules[module_name]
 
     def setUp(self):
-        self.test_dir = tempfile.mktemp()
-        os.mkdir(self.test_dir)
+        self.test_dir = tempfile.mkdtemp()
         sys.path.append(self.test_dir)
         self.package_dir = os.path.join(self.test_dir,
                                         self.package_name)
diff --git a/Lib/test/test_uu.py b/Lib/test/test_uu.py
index 75d1108..bb553a1 100644
--- a/Lib/test/test_uu.py
+++ b/Lib/test/test_uu.py
@@ -124,8 +124,7 @@
     verify(str(e) == 'No valid begin line found in input file')
 
 # Test to verify that decode() will refuse to overwrite an existing file
-import tempfile
-outfile = tempfile.mktemp()
+outfile = TESTFN + "out"
 inp = StringIO('Here is a message to be uuencoded')
 out = StringIO()
 uu.encode(inp, out, outfile)
diff --git a/Lib/test/test_wave.py b/Lib/test/test_wave.py
index a0e913c..1a6ff5c 100644
--- a/Lib/test/test_wave.py
+++ b/Lib/test/test_wave.py
@@ -1,5 +1,5 @@
-from test.test_support import TestFailed
-import os, tempfile
+from test.test_support import TestFailed, TESTFN
+import os
 import wave
 
 def check(t, msg=None):
@@ -11,9 +11,7 @@
 framerate = 8000
 nframes = 100
 
-testfile = tempfile.mktemp()
-
-f = wave.open(testfile, 'wb')
+f = wave.open(TESTFN, 'wb')
 f.setnchannels(nchannels)
 f.setsampwidth(sampwidth)
 f.setframerate(framerate)
@@ -22,7 +20,7 @@
 f.writeframes(output)
 f.close()
 
-f = wave.open(testfile, 'rb')
+f = wave.open(TESTFN, 'rb')
 check(nchannels == f.getnchannels(), "nchannels")
 check(sampwidth == f.getsampwidth(), "sampwidth")
 check(framerate == f.getframerate(), "framerate")
@@ -31,4 +29,4 @@
 check(input == output, "data")
 f.close()
 
-os.remove(testfile)
+os.remove(TESTFN)
diff --git a/Lib/test/test_whichdb.py b/Lib/test/test_whichdb.py
index 21f1588..2f1a3a2 100644
--- a/Lib/test/test_whichdb.py
+++ b/Lib/test/test_whichdb.py
@@ -11,7 +11,7 @@
 import tempfile
 import glob
 
-_fname = tempfile.mktemp()
+_fname = test.test_support.TESTFN
 
 def _delete_files():
     # we don't know the precise name the underlying database uses
diff --git a/Lib/toaiff.py b/Lib/toaiff.py
index cf0bfc8..35fbebb 100644
--- a/Lib/toaiff.py
+++ b/Lib/toaiff.py
@@ -75,7 +75,8 @@
 
 def _toaiff(filename, temps):
     if filename[-2:] == '.Z':
-        fname = tempfile.mktemp()
+        (fd, fname) = tempfile.mkstemp()
+        os.close(fd)
         temps.append(fname)
         sts = uncompress.copy(filename, fname)
         if sts:
@@ -98,7 +99,8 @@
     if ftype is None or not ftype in table:
         raise error, \
                 filename + ': unsupported audio file type ' + `ftype`
-    temp = tempfile.mktemp()
+    (fd, temp) = tempfile.mktemp()
+    os.close(fd)
     temps.append(temp)
     sts = table[ftype].copy(fname, temp)
     if sts:
diff --git a/Lib/urllib.py b/Lib/urllib.py
index 4d686b9..d367dd8 100644
--- a/Lib/urllib.py
+++ b/Lib/urllib.py
@@ -212,19 +212,21 @@
                 pass
         fp = self.open(url, data)
         headers = fp.info()
-        if not filename:
+        if filename:
+            tfp = open(filename, 'wb')
+        else:
             import tempfile
             garbage, path = splittype(url)
             garbage, path = splithost(path or "")
             path, garbage = splitquery(path or "")
             path, garbage = splitattr(path or "")
             suffix = os.path.splitext(path)[1]
-            filename = tempfile.mktemp(suffix)
+            (fd, filename) = tempfile.mkstemp(suffix)
             self.__tempfiles.append(filename)
+            tfp = os.open(fd, 'wb')
         result = filename, headers
         if self.tempcache is not None:
             self.tempcache[url] = result
-        tfp = open(filename, 'wb')
         bs = 1024*8
         size = -1
         blocknum = 1
diff --git a/Tools/compiler/regrtest.py b/Tools/compiler/regrtest.py
index aae0ec2..def07c2 100644
--- a/Tools/compiler/regrtest.py
+++ b/Tools/compiler/regrtest.py
@@ -15,15 +15,13 @@
 import tempfile
 
 def copy_test_suite():
-    dest = tempfile.mktemp()
-    os.mkdir(dest)
+    dest = tempfile.mkdtemp()
     os.system("cp -r %s/* %s" % (test.__path__[0], dest))
     print "Creating copy of test suite in", dest
     return dest
 
 def copy_library():
-    dest = tempfile.mktemp()
-    os.mkdir(dest)
+    dest = tempfile.mkdtemp()
     libdir = os.path.split(test.__path__[0])[0]
     print "Found standard library in", libdir
     print "Creating copy of standard library in", dest
diff --git a/Tools/faqwiz/faqwiz.py b/Tools/faqwiz/faqwiz.py
index 638da17..2e2a8b5 100644
--- a/Tools/faqwiz/faqwiz.py
+++ b/Tools/faqwiz/faqwiz.py
@@ -807,19 +807,19 @@
         f.close()
 
         import tempfile
-        tfn = tempfile.mktemp()
-        f = open(tfn, 'w')
-        emit(LOGHEADER, self.ui, os.environ, date=date, _file=f)
-        f.close()
+        tf = tempfile.NamedTemporaryFile()
+        emit(LOGHEADER, self.ui, os.environ, date=date, _file=tfn)
+        tf.flush()
+        tf.seek(0)
 
-        command = interpolate(SH_CHECKIN, file=file, tfn=tfn)
+        command = interpolate(SH_CHECKIN, file=file, tfn=tf.name)
         log("\n\n" + command)
         p = os.popen(command)
         output = p.read()
         sts = p.close()
         log("output: " + output)
         log("done: " + str(sts))
-        log("TempFile:\n" + open(tfn).read() + "end")
+        log("TempFile:\n" + tf.read() + "end")
         
         if not sts:
             self.prologue(T_COMMITTED)
diff --git a/Tools/idle/IOBinding.py b/Tools/idle/IOBinding.py
index 0ea4524..d80e53c 100644
--- a/Tools/idle/IOBinding.py
+++ b/Tools/idle/IOBinding.py
@@ -280,9 +280,11 @@
         if self.get_saved():
             filename = self.filename
         else:
-            filename = tempfilename = tempfile.mktemp()
+            (tfd, tfn) = tempfile.mkstemp()
+            os.close(tfd)
+            filename = tfn
             if not self.writefile(filename):
-                os.unlink(tempfilename)
+                os.unlink(tfn)
                 return "break"
         edconf = idleconf.getsection('EditorWindow')
         command = edconf.get('print-command')