将cmp()的结果保存到文件中

时间:2016-12-21 17:13:15

标签: python python-2.7 list file io

我尝试在某些列表上运行三向比较,然后将差异存储在文件中。下面是我到目前为止的代码。我无法弄清楚如何将丢失的文件(如果找到)保存到文本文件中。

我也知道比较代码不是最佳的,但我是编程新手,只是尝试不同的东西。如果有人有更好的想法让我知道。我来这里学习。

比较代码

def three_way_compare(startup, running, archive):
    if cmp(startup, archive) and cmp(running, archive) != 0:
        print "Archive File Missing: "
        print set(startup)^set(archive)
    elif cmp(startup, archive) != 0:
        print "Startup File Missing: "
        print "File missing: " 
        print set(startup)^set(archive)
    elif cmp(running, archive) != 0:
        print "Running File Missing: "
        print set(running)^set(archive)
    elif cmp(running, startup) != 0:
        print "Running and Startup do not match"
        print "Missing Files: " 
        print set(running)^set(startup)
    else:
        print "All Files match" 

编写文件代码

def write_diff_file():
    from datetime import datetime
    datestring = datetime.strftime(datetime.now(), '%Y-%m-%d')
    f = open('filediff_' + datestring + '.txt', 'w')
    f.name   

类似的东西,

如果three_way_compare == True#返回差异 然后用当前日期写入带有差异的文件

我想我已经通过这样做解决了它。

更新比较代码:

def three_way_compare(startup, running, archive):
    isdiff = True
    if cmp(startup, archive) and cmp(running, archive) != 0:
        print "Archive File Missing: "
        compareset = set(startup)^set(archive)
    elif cmp(startup, archive) != 0:
        print "Startup File Missing: " 
        compareset = set(startup)^set(archive)
    elif cmp(running, archive) != 0:
        print "Running File Missing: "
        compareset = set(running)^set(archive)
    elif cmp(running, startup) != 0:
        print "Running and Startup do not match"
        compareset = set(running)^set(startup)
    else:
        print "All Files match" 
        isdiff = False
    if isdiff == True:
        write_diff_file(compareset)

更新了写入文件代码:

def write_diff_file(x):
    from datetime import datetime
    datestring = datetime.strftime(datetime.now(), '%Y-%m-%d')
    with open('filediff_' + datestring + '.txt', 'w') as f:
        f.write(str(x))
        f.name   

1 个答案:

答案 0 :(得分:0)

你可以这样做:

content = 'what I want to save'
with open('myfile.txt', 'w') as logfile:
    logfile.write(content)  # the 'with' keyword will close the file for you