[Tutor] Re: dynamically creating files
Andrei
project5 at redrival.net
Fri Nov 14 08:14:57 EST 2003
Don Arnold wrote on Fri, 14 Nov 2003 06:39:47 -0600:
<snip>
>> 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 :
>
<snip>
> 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)
<snip>
That's a wrapper for the file class which doesn't do a lot more than the
file class itself. If it's necessary to have lines appear on the screen as
well as in the file, it's better to subclass the file class and add that
behaviour instead of making a new one from scratch. E.g.:
>>> class myfile(file):
... def write(self, line="\n"):
... """Writes a line and appends "\n" if necessary."""
... if line[-1]!="\n": # append newline
... line = line + "\n"
... print line,
... file.write(self, line)
...
>>> mf = myfile("deleteme.txt", "w")
>>> mf.write("bla")
bla
>>> mf.write("bla\n")
bla
>>> mf.close()
>>> mf
<closed file 'deleteme.txt', mode 'w' at 0x016B2088>
--
Yours,
Andrei
=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.
More information about the Tutor
mailing list