new file.write method

David Bear david.bear at asu.edu
Mon Nov 3 19:29:25 EST 2003


I'd like something like the versioning behavior in emacs for the
file.write method.  I spent some time looking around parnassus and
couldnt find anything there.  Google for "python file version method"
was useless.  Looking at the lib reference, there don't seem to be any
addition methods/attributes available for the file.write method.

what I would like is a write method that each time is was called it
would look for an existing file by that name, if it existed rename it
to file.~n~ and then procede to write the current to file.  of course
it would be neat if one could also specify the maxversions as well,
something like
  file.write("name", maxver=10) 
would be perfect.  

I've been trying to write a library to do this myself but hit a few
snags.  I realized there's more to this than I originally thought.  I
wanted to try to use recursion to handle this.. but the code turned
real ugly.  Here's what I have so far.  

#!/usr/bin/python
#
import sys, os, os.path

def makeVer(filename, count=0, max=10):
    ''' makes versions of filename, filename must
    have a trailing . (period), the splitext function is used
    without intelligence, upon success, filename is return, on any
    IOexception, None is returned
    '''
    try:
        if count == max-1:
            # print 'remove lastver'
            os.remove(filename)
        if os.path.exists(filename):
            count += 1
            nn = os.path.splitext(filename)[0] + '.~%s~' % count
            dummy = makeVer(nn, count)
            os.rename(filename, nn)
            print "renaming " + filename
        else:
            # no prior versions exists under this name
            pass
    except IOError:
        return(None)
    return(filename)

def callMakeVer(filename, maxVersions=10, debug=0):
    ''' wraps makeVer to check for first use, as well as file name
    dependancies, checks proper returns of makeVer, returns proper
    file object or None on error
    '''
    try:
        if os.path.exists(filename):
            if filename[len(filename)-1] == '.':
                name = filename + '.'
            else:
                name = filename
            result = makeVer(name, 0, maxVersions)
            if result == None:
                return(result)
        result = open(filename, 'w')
    except IOError:
        return(result)
    return(result)
            

                
if __name__ == "__main__":
    fn = sys.argv[1]
    dummy = callMakeVer(fn)
    if dummy == None:
        print "stupid"
    print type(dummy)
    print dummy




More information about the Python-list mailing list