import os import tempfile fd, path = tempfile.mkstemp() try: with os.fdopen(fd, 'w') as tmp: # do stuff with temp file tmp.write('stuff') finally: os.remove(path)