记忆角落

  • {{ item.name }}
  • 代码部分:
  • 首页
  • 关于
  • 归档
  • 邻居
  • 捐赠

(python)两文件行数内容对比,输出二者不存在的内容

  • 郭良俊只狗
  • 2021-03-14
  • 0

代码部分:

#!/usr/bin/env python3
# _*_ coding:utf-8 _*_
"""
两文件行数内容对比,输出二者不存在的内容
"""
import datetime
import os


def check_file(file1, file2):
    time = str(datetime.datetime.now().strftime("%Y%m%d%H%M%S"))

    file1_name = os.path.split(file1)[1]
    file2_name = os.path.split(file2)[1]

    str1 = []
    str2 = []
    str_dump = []
    f1 = open(file1, 'r', encoding='UTF-8')
    f2 = open(file2, 'r', encoding='UTF-8')

    for line in f1.readlines():
        str1.append(line.replace("\n", ''))

    for line in f2.readlines():
        str2.append(line.replace("\n", ''))
    f1.close()
    f2.close()

    for i in str1:
        if i not in str2:
            i = file1_name+','+i
            str_dump.append(i)

    for i in str2:
        if i not in str1:
            i = file2_name+','+i
            str_dump.append(i)

    # f3 = open('target_{}.txt'.format(time), 'w+')
    # for i in list(str_dump):
    #     f3.write(i + '\n')
    # f3.close()

    with open('target_{}.txt'.format(time), 'w+') as f3:
        for i in list(str_dump):
            f3.write(i + '\n')


if __name__ == '__main__':
    check_file("1.txt", "2.txt")

 

© 2012 - 2023 记忆角落 网站统计
Theme by Wing
粤ICP备14056850号-1 又拍云CDN赞助