python 解压/压缩文件夹/移动文件

596 阅读1分钟
import os
import zipfile
import shutil


# python 解压文件到指定文件夹下
unzip_command = f'unzip -O cp936 {repr(origin_file_path)} -d {repr(unzip_full_file_path)}'
os.system(unzip_command)  # todo os.system
            
def unzip_file(self, origin_file_path, unzip_file_path):
    """
    解压缩
    """
    try:
        with zipfile.ZipFile(origin_file_path) as zf:
            zf.extractall(path=unzip_file_path)
    except Exception as e:
        raise e

def zipDir(self, dirpath, outFullName):
    """
    压缩指定文件夹
    :param dirpath: 目标文件夹路径
    :param outFullName: 压缩文件保存路径+xxxx.zip
    :return: 无
    """
    try:
        zip = zipfile.ZipFile(outFullName, "w", zipfile.ZIP_DEFLATED)
        for path, dirnames, filenames in os.walk(dirpath):
            # 去掉目标跟路径,只对目标文件夹下边的文件及文件夹进行压缩
            fpath = path.replace(dirpath, '')

            for filename in filenames:
                zip.write(os.path.join(path, filename), os.path.join(fpath, filename))
        zip.close()
    except:
        logger.error(traceback.format_exc())

def move_file(self, src_path: str, dst_path: str):
    try:
        file_path, file_name = os.path.split(dst_path)  # 分离文件名和路径
        if not os.path.exists(file_path):
            os.makedirs(file_path)  # 创建路径
        shutil.move(src_path, dst_path)  # 移动文件
        return file_name
    except Exception as e:
        traceback.print_exc()
        raise e