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')
        
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章