[Tutor] dynamically creating files
Don Arnold
darnold02 at sprynet.com
Fri Nov 14 07:39:47 EST 2003
----- Original Message -----
From: "bob" <nospam at 245t.com>
To: <tutor at python.org>
Sent: Friday, November 14, 2003 8:38 AM
Subject: [Tutor] dynamically creating files
> 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
>
Would something like this work? It's not too thoroughly tested, but it might
be a starting point :
import os
def getNewFile(dirStr):
for i in xrange(0,1000):
testname = '/'.join([dirStr,'filer%04d' % i])
try:
f = open(testname,'r')
f.close()
except IOError:
f = open(testname,'w')
return (f,testname)
class Filer(object):
def __init__(self,targetDir):
self.myfile, self.myfilename = getNewFile(targetDir)
print 'using ', self.myfilename
def writeLines(self):
for i in range(10):
txt = 'writing line %d to %s...' % (i, self.myfilename)
print txt
self.myfile.write(txt+'\n')
def closeMyFile(self):
self.myfile.close()
if __name__ == '__main__':
filer1 = Filer('c:/temp2')
filer1.writeLines()
filer1.closeMyFile()
filer2 = Filer('c:/temp2')
filer2.writeLines()
filer2.closeMyFile()
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list