简体   繁体   English

覆盖文件或追加

[英]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. 如果文件确实存在,则将其覆盖,但是会保存原始文件或将新文件增加1。

Naming format is yyyymmdd, so if existing it would create a new file called yyymmdd-v2 or something like that. 命名格式为yyyymmdd,因此如果存在,它将创建一个名为yyymmdd-v2或类似名称的新文件。

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"

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:
    ....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM