NineTail
NineTail

Reputation: 223

Overwrite File or Append

Need a single function that will write a file if one does not exist. Overwrite the file if it does exist, but saves the original or incriments the new file by 1.

Naming format is yyyymmdd, so if existing it would create a new file called yyymmdd-v2 or something like that.

This is what I have currently.

def write_diff_file(x):
    from datetime import datetime
    datestring = datetime.strftime(datetime.now(), '%Y_%m_%d') 
    try:
        with open("./%s" % 'filediff_' + datestring + '.txt', 'a') as f:
            line = str(x).replace("archive\\", "")
            f.write(line)
            f.write("\n")
            f.name
        #print "Comparison File Written"
    except IOError as (errno, strerror):
        print "I/O error({0}): {1}".format(errno, strerror)
        print "Error in write_diff_file function"

Upvotes: 0

Views: 230

Answers (1)

Julien Spronck
Julien Spronck

Reputation: 15423

You want to check whether the file exists and adapt the filename if it already does. Something like this should work:

import os
from datetime import datetime

datestring = datetime.strftime(datetime.now(), '%Y_%m_%d')
filename = 'filediff_' + datestring + '.txt'
filenb = 1
while os.path.exists(filename):
    filenb += 1
    filename = 'filediff_{0}_v{1}.txt'.format(datestring, filenb)
with open(filename, 'w') as f:
    ....

Upvotes: 1

Related Questions