Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

The tempfile Module

One common problem is to open a unique temporary file to hold intermediate results. There are two ways to do this: the os module and the tempfile module. The os module has a subtle security flaw, so it isn't recommended.

The tempfile module creates a temporary file in the most secure and reliable manner. The tempfile module includes an internal function, mkstemp which dioes the hard work of creating a unique temporary file.

tempfile.TemporaryFile〈 mode 〉〈 suffix 〉〈 prefix 〉〈 directory file

This function creates a file which is automatically deleted when it is closed. All of the parameters are optional. By default, the mode is 'w+b', allowing updating. The keyword parameters suffix , prefix and directory provide some structure to the name assigned to the file. The suffix should include the dot, for example suffix='.tmp'.

tempfile.NamedTemporaryFile〈 mode 〉〈 suffix 〉〈 prefix 〉〈 directory file

This function is similar to TemporaryFile; it creates a file which is automatically deleted when it is closed. The temporary file, however, is guaranteed to be visible on the file system while the file is open.

tempfile.mkstemp〈 suffix 〉〈 prefix 〉〈 directory fd , file

This function does the essential job of creating a temporary file. It returns a file descriptor as well as the name of the file. The file is not automatically deleted. If necessary, the file created by this function can be explicitly deleted with os.remove.

import tempfile, os
fd, tempName = tempfile.mkstemp( '.d1' )
temp= open( tempName, 'w+' )


Some Processing...

This fragment will create a unique temporary file name with an extension of .d1. Since the name is guaranteed to be unique, this can be used without fear of damaging or overwriting any other file.


 
 
  Published under the terms of the Open Publication License Design by Interspire