[Tutor] file opening modes

Mehta, Anish Anish.Mehta at enst-bretagne.fr
Thu Sep 11 12:25:58 EDT 2003


I have a suggestion also though i am not an expert in python.  I have 
tried to solve the problem like this: as i have taken a dictionary and i 
am inserting the filenames which i am creating dynamically. And if you 
open the file for the first time use the 'w' mode otherwise insert the 
filename into the dictionary and use the 'a' mode. This way you will 
automatically delete the file when you create it for the first time 
because we are using write mode for the first time.

class XYZ:
        def __init__(self):
                self.fileList = {}
                self.key = 0
       
       

        def writefile(self,data):
                filename = '%s-%s.txt' % (fontname,tag)

        #Check whether this file has already been opened or not.
       
                if filename in self.fileList.values():
                        mode = 'a'
                else:
                        self.fileList[self.key] = filename
                        mode = 'w'
                        self.key = self.key+1

                outfile = file(filename, mode)
                outfile.write(data)
                outfile.close()


I hope i am right!!!
Suggestions from tutor will make it more suitable for you to use.


Thanks a lot.

Regards,

Anish

Alan Gauld wrote:

>>i.e. append mode so that i can append information to the file while
>>    
>>
>i am
>  
>
>>running the program.
>>    
>>
>
>Yes thats the right approach.
>
>  
>
>>and three files are generated
>>
>>a.txt, b.txt, c.txt
>>
>>
>>Now suppose if i run the program again then i get into problem
>>    
>>
>because now
>  
>
>>again these three files will be appending the information in the
>>    
>>
>existing
>  
>
>>files which i created last time i run the program.
>>    
>>
>
>OK so you need to add a tst for file existence before opening it.
>Then if it already exists (and the datestamp is within T seconds
>of the current time) then use append othewise use 'w' which will
>overwrite the old version.
>
>Alternatively do some housekeeping first and copy the old file to
>a .bak before creating the new one.
>
>Put the test in a function:
>
>def alreadyExists(fname):
>    # test here
>
>then your code looks like:
>
>if alreadyExists(fname): mode = 'a'
>else: mode = 'w'
>f = open(fname,mode)
>
>HTH,
>
>Alan g
>
>
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>
>  
>

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20030911/fe7a4938/attachment.htm


More information about the Tutor mailing list