【问题标题】:Save results of cmp() to file将 cmp() 的结果保存到文件
【发布时间】:2017-05-07 04:54:10
【问题描述】:

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

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

比较代码

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   

类似的,

if 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   

【问题讨论】:

    标签: python python-2.7 list file io


    【解决方案1】:

    你可以这样做:

    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
    

    【讨论】:

    • 这将在正常写入下工作。但是我希望文件以某个文件名的形式写入,并且仅在发现差异时才写入。不同之处在于写入文件的内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-15
    • 2019-03-25
    相关资源
    最近更新 更多