栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何逐行比较两个不同的文件并在第三个文件中写入差异?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何逐行比较两个不同的文件并在第三个文件中写入差异?

如果您使用的是* nix系统,最好的通用选项只是使用:

sort filea fileb | uniq -u

但是,如果您需要使用Python:

您的代码在外部文件的每次迭代中都会重新打开内部文件。在循环外打开它。

使用嵌套循环比循环遍历第一个存储找到的值,然后将第二个与这些值进行比较的效率低。

def build_set(filename):    # A set stores a collection of unique items.  Both adding items and searching for them    # are quick, so it's perfect for this application.    found = set()    with open(filename) as f:        for line in f: # [:2] gives us the first two elements of the list. # Tuples, unlike lists, cannot be changed, which is a requirement for anything # being stored in a set. found.add(tuple(sorted(line.split()[:2])))    return foundset_more = build_set('100rwsnMore.txt')set_del = build_set('100rwsnDeleted.txt')with open('results.txt', 'w') as out_file:   # Using with to open files ensures that they are properly closed, even if the pre   # raises an exception.   for res in (set_more - set_del):      # The - computes the elements in set_more not in set_del.      out_file.write(" ".join(res) + "n")


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/651455.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号