[Tutor] dynamically creating files

Jeff Shannon jeff at ccvcorp.com
Fri Nov 14 13:28:49 EST 2003

bob wrote:
> I am creating a program and have come to a problem. 
> I wish to write a class that handles file objects, ie opening, writing to,
> and closing a file. I wish to dynamically create the file name, as each
> instance would have its own file too use for processing. I am not sure on
> what syntax is required to derive a filename from the 'self' instance. 
> Any tips/ TIA

Instead of trying to derive a filename from 'self', why not use the 
tempfile module?  This will give you a file with a guaranteed unique 

self.filename = tempfile.mktemp('.ext')
fileobj = file(self.filename, "w+b")

This will give you a fully qualified filename of a file that does not 
exist at the time mktemp() is called, and ensures that the filename 
will end in '.ext' (or whatever you pass as an argument).  You can 
also control the directory that the tempfile is created in.

Jeff Shannon
Credit International

More information about the Tutor mailing list