20 天学 Python 文件操作:Day 8 压缩与解压文件

liftword4个月前 (03-03)技术文章34

在日常开发中,压缩和解压文件是处理文件操作的常见需求。Python 提供了丰富的内置模块,比如 zipfile 和 shutil,让我们能够高效地压缩和解压文件。今天我们将学习如何使用这些模块进行操作。


1. 使用 zipfile 模块压缩文件

zipfile 模块是 Python 标准库的一部分,用于创建和读取 ZIP 格式的文件。

压缩单个文件

import zipfile

def compress_file(file_path, zip_path):
    with zipfile.ZipFile(zip_path, 'w') as zipf:
        zipf.write(file_path, arcname=file_path.split('/')[-1])
    print(f"文件 {file_path} 已压缩到 {zip_path}")

# 示例
compress_file("example.txt", "example.zip")

压缩多个文件

def compress_files(file_paths, zip_path):
    with zipfile.ZipFile(zip_path, 'w') as zipf:
        for file_path in file_paths:
            zipf.write(file_path, arcname=file_path.split('/')[-1])
    print(f"文件 {file_paths} 已压缩到 {zip_path}")

# 示例
compress_files(["example1.txt", "example2.txt"], "examples.zip")

2. 使用 zipfile 模块解压文件

解压 ZIP 文件同样简单。

解压到指定目录

def decompress_file(zip_path, extract_dir):
    with zipfile.ZipFile(zip_path, 'r') as zipf:
        zipf.extractall(extract_dir)
    print(f"文件 {zip_path} 已解压到 {extract_dir}")

# 示例
decompress_file("example.zip", "extracted")

列出压缩文件的内容

def list_zip_contents(zip_path):
    with zipfile.ZipFile(zip_path, 'r') as zipf:
        print("压缩文件内容:")
        print(zipf.namelist())

# 示例
list_zip_contents("example.zip")

3. 使用 shutil 模块压缩文件夹

shutil 模块提供了更高层次的压缩功能,支持多种压缩格式。

压缩整个文件夹为 ZIP 文件

import shutil

def compress_folder(folder_path, zip_path):
    shutil.make_archive(zip_path, 'zip', folder_path)
    print(f"文件夹 {folder_path} 已压缩到 {zip_path}.zip")

# 示例
compress_folder("example_folder", "example_folder_compressed")

注意:此方法会压缩文件夹及其所有子目录。

解压文件夹

使用 shutil 解压需要搭配 unpack_archive。

def decompress_folder(zip_path, extract_dir):
    shutil.unpack_archive(zip_path, extract_dir)
    print(f"文件 {zip_path} 已解压到 {extract_dir}")

# 示例
decompress_folder("example_folder_compressed.zip", "decompressed_folder")

4. 练习任务

  1. 编写一个函数 create_backup(zip_path, folder_paths),将多个文件夹压缩到一个 ZIP 文件中。
  2. 编写一个函数 extract_specific_file(zip_path, file_name, extract_dir),从 ZIP 文件中解压特定的文件。

示例代码框架

def create_backup(zip_path, folder_paths):
    with zipfile.ZipFile(zip_path, 'w') as zipf:
        for folder in folder_paths:
            for root, _, files in os.walk(folder):
                for file in files:
                    full_path = os.path.join(root, file)
                    zipf.write(full_path, arcname=os.path.relpath(full_path, folder))

def extract_specific_file(zip_path, file_name, extract_dir):
    with zipfile.ZipFile(zip_path, 'r') as zipf:
        if file_name in zipf.namelist():
            zipf.extract(file_name, extract_dir)
            print(f"文件 {file_name} 已解压到 {extract_dir}")
        else:
            print(f"文件 {file_name} 不在 {zip_path} 中")

通过今天的学习,你已经掌握了如何使用 Python 处理压缩和解压操作。明天我们将学习更高级的文件读写操作技巧,敬请期待!

相关文章

最全RAR文件操作指南:如何用Python压缩、解压与筛选文件

引言:Python 对 .rar 文件进行压缩、解压以及筛选特定文件的操作代码封装一下import os import rarfile #todo 用于处理 RAR 文件 import zipfil...

20 天学 Python 文件操作:Day 16 文件压缩与解压

在日常工作中,我们经常需要对文件进行压缩和解压操作以减少存储空间或方便文件传输。今天,我们将学习如何使用 Python 进行文件的压缩与解压。1. 使用 zipfile 模块进行 ZIP 文件操作创建...

Python全能压缩:ZIP的压缩、解压、文件筛选与删除,一键搞定!

引言:这个方法实现了文件压缩与解压的常见操作,涵盖内容如下:1、从文件夹创建 ZIP 文件 2、从文件夹创建 ZIP 文件(筛选特定文件) 3、解压 ZIP 文件中的所有内容 4、解压 ZIP...

python压缩/解压gzip 大文件

最近处理线上日志,日志文件刚好是经过压缩的,且是gz后缀。自己便采用gzip库来处理。示例如下:创建gzip文件# -- coding: utf-8 -- import gzip """ 创建gzi...

使用 Python 在 Excel 中插入、压缩、替换、提取和删除图像

Excel 不仅仅是一个数字和公式的工具;它还提供了用于处理图像的强大功能。无论您是创建报告、演示文稿还是数据可视化,合并图像都可以大大提高 Excel 项目的整体影响力和专业性。在 Excel 中...

Python打包成 exe,太大了该怎么解决?

有个刚毕业的小学妹问,Python打包成exe,太大了该怎么解决?首先要知道Python打包exe为什么这么大?我猜你一定是用PyInstaller打包exe的,PyInstaller特点是将乱七八糟...