> ## Content Index
> Fetch the complete content index at: https://lucent.blog/llms.txt
> Use this file to discover other available public pages before exploring further.

# Python解压缩
- URL: https://lucent.blog/pythonjie-ya-suo/
- Published: 2020-06-12T04:12:50.000Z
- Updated: 2026-08-21T00:49:55.000Z
- Author: Lucent
- Tags: Python

解压一个.zip文件或一个目录下的所有.zip文件到指定目录。

运行方法：`python unzip.py "source_dir" "dest_dir" password`

参数说明：

```
    source_dir和dest_dir既可以绝对路径也可以为相对路径。
    source_dir和dest_dir的缺省值表示当前目录。
    password缺省表示压缩文件未加密。

```

代码：

```
import sys, os, zipfile

def unzip_single(src_file, dest_dir, password):
    """
     解压单个文件到目标文件夹。
    """
    if password:
        password = password.encode()
    zf = zipfile.ZipFile(src_file)
    try:
        zf.extractall(path=dest_dir, pwd=password)
    except RuntimeError as e:
        print(e)
    zf.close()

def unzip_all(source_dir, dest_dir, password):
    if not os.path.isdir(source_dir):  # 如果是单一文件
        unzip_single(source_dir, dest_dir, password)
    else:
        it = os.scandir(source_dir)
        for entry in it:
            try:
                if entry.is_file() and os.path.splitext(entry.name)[1] == '.zip':
                    unzip_single(entry.path, dest_dir, password)
                    print(entry.name+" 解压完成")
            except Exception as e:
                print(str(e)+": "+entry.name)
                with open(source_dir + "\\UnzipFailed.txt", 'a') as log:
                    log.write(entry.name + "\n")
                pass
            continue

if __name__ == "__main__":

    # 获取源路径和目标路径
    source_dir = "C:\\Users\\user\\Desktop\\新建文件夹"
    dest_dir = "C:\\Users\\user\\Desktop\\新建文件夹\\111"
    password = None
    if len(sys.argv) == 2:  # 指定了压缩文件所在路径
        source_dir = sys.argv[1]
    if len(sys.argv) == 3:  # 压缩文件所在和解压到路径均指定
        source_dir, dest_dir = os.path.abspath(sys.argv[1].strip('"')), os.path.abspath(sys.argv[2].strip('"'))
    if len(sys.argv) == 4:  # 还指定了密码
        source_dir, dest_dir, password = os.path.abspath(sys.argv[1].strip('"')), os.path.abspath(
            sys.argv[2].strip('"')), sys.argv[3]
    if len(sys.argv) > 4:
        print('过多的参数，可能是路径中有空白字符，请用""将路径括起。')
        exit()

    print("源目录:", source_dir)
    print("解压到:", dest_dir)
    print("解压密码:", password)

    # 判断源路径是否合法
    if not os.path.exists(source_dir):
        print("压缩文件或压缩文件所在路径不存在！")
        exit()
    if not os.path.isdir(source_dir) and not zipfile.is_zipfile(source_dir):
        print("指定的源文件不是一个合法的.zip文件！")
        exit()

    # 如果解压到的路径不存在，则创建
    if not os.path.exists(dest_dir):
        os.mkdir(dest_dir)

    unzip_all(source_dir, dest_dir, password)

```