Python的交集差集并集返回多个值进行处理遍历

Python的交集差集并集返回多个值进行处理遍历

  • 代码实现
import os

def reader_file(path):
    #解决乱码问题
    fi = open(path,'r',encoding='utf-8',errors = 'ignore')
    strs=[]
    #splitlines解决不换行\n输出
    for line in fi.read().splitlines():
        if(len(line)>0):
           strs.append(line)
    return strs

#并集,交集,差集方法处理
def find_diff_str(list1,list2):
    A = set(list1).intersection(set(list2)) #交集
    B = set(list1).union(set(list2)) # 并集
    C = set(list1).difference(set(list2)) #差集,在list1中但不在list2中的元素
    D = set(list2).difference(set(list1)) #差集,在list2中但不在list1中的元素
    return A,B,C,D

"""
通过指定文件路径文件进行读取内容
如:D:\test\file.txt
"""
def reader_file(path):
    #解决乱码问题
    fi = open(path,'r',encoding='utf-8',errors = 'ignore')
    strs=[]
    #splitlines解决不换行\n输出
    for line in fi.read().splitlines():
        if(len(line)>0):
            strs.append(line)
    return strs

#指定文件路径获取文件最后文件的路径包含文件
#如:D:\test\file.txt 返回的结果为:D:\test\
def get_file_root(path):
    #获取文件名
    #return os.path.split(path)[1] 
    # 获取文件路径
    return os.path.split(path)[0]   
# 创建目录
def mkdir(path):
    # 去除尾部 \ 符号
    pathx = path.strip().rstrip("\\")
    # 判断路径是否存在
    # 存在     True
    # 不存在   False
    isExists = os.path.exists(pathx)
    # 判断结果
    if not isExists:
        # 如果不存在则创建目录创建目录操作函数
        os.makedirs(path)
        print(path + ' 创建成功')
        return True
    else:
        # 如果目录存在则不创建,并提示目录已存在
        print(path + ' 目录已存在')
        return False


# 创建一个txt文件,并向文件写入msg
"""
@file_dir参数 代表文件目录 如:D:\test
@file_name参数 代表文件名称 如:file.txt
@msg参数 代表要写入文件的内容信息
"""
def writer_to_file(file_dir, file_name, msg):
    # 先创建目录
    mkdir(file_dir)
    # 再打开文件
    full_path = file_dir + "\\" + file_name
    fi = open(full_path, 'w')
    # 写入文件
    fi.write(msg) 
    fi.close()


if __name__ == '__main__':
   
    base_path =r'C:\Users\Desktop\Py\test\1.txt'
    base_path1 =r'C:\Users\Desktop\Py\test\2.txt'
    list1=reader_file(base_path)
    list2=reader_file(base_path1)
    #遍历接收
    A,B,C,D = find_diff_str(list1,list2)
    
    strx = ''
   #也可以这样写   
   # for c in A,B,C,D:
    for c in C:
      #这里是处理数字才用str进行转换字符串拼接
       strx+=str(c)+'\n'
    
    new_path = get_file_root(base_path1)
    #不存在就创建目录
    mkdir(new_path)
    #写入文件
    writer_to_file(new_path, "list.txt", strx)
    
    print(f'do finish')
        
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章