Python操作文件封裝工具類 Python操作文件封裝

Python操作文件封裝

  • 解壓文件
  • 刪除文件
  • 寫入文件
  • 遞歸文件
  • 解決亂碼
  • 刪除目錄
  • 創建目錄
  • 去重數據
# -*- coding:utf-8 -*-
import os
import re
import time
import operator
import zipfile
import rarfile
import shutil

# 找交集,差集
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
 

# 對個獲取指定目錄的所有文件
def get_all_files(dir):
    fileList = []
    """遍歷獲取指定文件夾下面所有文件"""
    if os.path.isdir(dir):
        filelist = os.listdir(dir)
        for ret in filelist:
            filename = dir + "\\" + ret
            if os.path.isfile(filename):
                fileList.append(filename)
    return fileList


# 對個獲取指定目錄的所有文件
def get_file_list_by_walk(dir):
    fileList = []
    """使用listdir循環遍歷"""
    if not os.path.isdir(dir):
        return fileList
    dirlist = os.walk(dir)
    for root, dirs, files in dirlist:
        for fi in files:
            fileList.append(os.path.join(root, fi))
    return fileList

#指定文件路徑獲取文件最後文件的路徑包含文件
#如:D:\test\file.txt 返回的結果爲:D:\test\
def get_file_root(path):
    #獲取文件名
    #return os.path.split(path)[1] 
    # 獲取文件路徑
    return os.path.split(path)[0]

#指定文件路徑獲取文件最後文件的路徑包含文件
#如:D:\test\file.txt 返回的結果爲:file.txt
def get_file_name(path):
    return os.path.basename(path)
    
# 編碼轉換
def decode(str):
    try:
        string = str.encode('cp437').decode('gbk')
    except:
        string = str.encode('utf-8').decode('utf-8')
    return string  
# 創建目錄
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


"""
參考文章 https://www.jb51.net/article/180325.htm
https://blog.csdn.net/WANGYONGZIXUE/article/details/111576380
在一個數組裏面找重複值
python處理去重用set函數
"""
def find_repeat_val_by_list(list):
    values = {}
    for i in list:
      if list.count(i)>1:
        values[i] = list.count(i)
    return values

"""
通過指定文件路徑文件進行讀取內容
如: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 str

"""
創建一個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()




#刪除文件
def del_files(dir_path):
    # os.walk會得到dir_path下各個後代文件夾和其中的文件的三元組列表,順序自內而外排列,
    for root, dirs, files in os.walk(dir_path, topdown=False):
        # 第一步:刪除文件
        for file_name in files:
            try:
                os.remove(os.path.join(root, file_name))  # 刪除文件
            except Exception as e:
                print(f'刪除文件,失敗原因爲:{e}' )
                pass
    
        # 第二步:刪除空文件夾
        for dir in dirs:
            #判斷目錄不存在PDF就刪除
            try:
                os.rmdir(os.path.join(root, dir)) # 刪除一個空目錄
            except Exception as e:
                print(f'刪除空文件夾,失敗原因爲:{e}' )
                pass
                    
# 創建目錄
def mkdir(path):
    # 去除尾部 \ 符號 
    pathx = path.strip().rstrip("\\")
    #print(f'pathx={pathx}')
    
    # 判斷路徑是否存在
    # 存在     True
    # 不存在   False
    isExists = os.path.exists(pathx)
    # 判斷結果
    if not isExists:
        # 如果不存在則創建目錄創建目錄操作函數
        os.makedirs(path)
        print(path + ' 創建成功')
        return True
    else:
        # 如果目錄存在則不創建,並提示目錄已存在
        print(path + ' 目錄已存在')
        return False
        

class File:
    def __init__(self):
        self.fileList = []

    """
    遞歸列表文件
    """
    def recursion_file(self, filepath):
        files = os.listdir(filepath)
        for file in files:
            fi_d = os.path.join(filepath, file)
            if os.path.isdir(fi_d):
                self.recursion_file(fi_d)
            else:
                self.fileList.append(fi_d)

    """
    獲取文件列表
    """

    def get_file_list(self, filepath):
        self.recursion_file(filepath)
        return self.fileList

"""
解壓rar文件
需要安裝WinRar並且配置環境變量
pip install rarfile
返回失敗文件
"""
def un_rar(filepath):
    fail_path = ''
    try:
        if os.path.isdir(filepath + "-file"):
            pass
        else:
            zipname = filepath
            extractpath = filepath.replace(".rar", "") + '-file'
            rar = rarfile.RarFile(zipname)
            rar.extractall(extractpath)
            rar.close()
            #os.remove(extractpath)
            #print(f'成功文件:{get_file_name(filepath)}' )
    except Exception as e:
        print(f'失敗文件爲:{get_file_name(filepath)}--->>un_rar Exception file fail' )
        fail_path = filepath
        pass
    return fail_path

# 不就刪除原來解壓之後的文件
def del_empty_file(dir_path):
    for root, dirs, files in os.walk(dir_path, topdown=False):
        # 第二步:刪除空文件夾
        for dir in dirs:
            #判斷目錄不存在PDF就刪除
            try:
                os.rmdir(os.path.join(root, dir)) # 刪除一個空目錄
            except Exception as e:
                print(f'刪除空文件夾,失敗原因爲:{e}' )
                pass
"""
解壓zip文件 返回失敗文件
"""
def un_zip(filepath):
    fail_path = ''
    # 可以自己定義路徑
    zipname = filepath
    extractpath = filepath.replace(".zip", "") + '-file'
    try:
       
        # 注意壓縮格式選擇
        frzip = zipfile.ZipFile(zipname, 'r', zipfile.ZIP_DEFLATED)
        # 將所有文件加壓縮到指定目錄
        frzip.extractall(extractpath)
        frzip.close()
    except Exception as e:
        print(f'失敗文件爲:{get_file_name(filepath)}' )
        fail_path = filepath
        pass
    
    #解壓完成
    all_path_file = []
    all_path_dir = []
    for root, dirs, files in os.walk(extractpath):
        for file in files:
            file_kv = {'name': file, 'path': root}
            all_path_file.append(file_kv)
        for dir1 in dirs:
            # 文件深度
            deep_count = len(root.split('\\'))
            dir_kv = {'name': dir1, 'path': root, 'deep': deep_count}
            all_path_dir.append(dir_kv)
    # 一定是先文件再文件夾,否者重命名後文件夾內的文件找不到,先是最大深度文件夾,所以需要深度排序
    all_path_dir = sorted(all_path_dir, key=operator.itemgetter('deep'), reverse=True)

    for dic in all_path_file + all_path_dir:
        file_name   = dic['name']
        parent_path = dic['path']
        file_name_ok  = decode(file_name)  
        err_path_name = os.path.join(parent_path, file_name)
        ok_path_name  = os.path.join(parent_path, file_name_ok)
        os.rename(err_path_name, ok_path_name)  # 重命名文件
        
    return fail_path


#刪除空文件夾
def del_file(dir_path):
    for root, dirs, files in os.walk(dir_path, topdown=False):
        # 第二步:刪除空文件夾
        for dir in dirs:
            try:
                print(f'dir-->{dir}')
                os.rmdir(os.path.join(root, dir)) # 刪除一個空目錄
            except Exception as e:
                print(f'刪除空文件夾,失敗原因爲:{e}' )
                pass

    print('刪除空文件完成')

python讀取Excel推薦文章

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章