10个Python文件压缩与解压实战技巧

文末赠免费精品编程资料~~

在日常开发和数据处理中,文件的压缩与解压是一项基础而实用的技能。Python通过zipfiletarfile模块提供了强大的文件压缩和解压缩功能。下面,我们将通过10个实战技巧,一步步深入学习如何高效地操作文件压缩包。

技巧1: 创建ZIP压缩文件

目标: 将多个文件或目录打包成一个ZIP文件。

import zipfile

def create_zip(zip_name, files):
    with zipfile.ZipFile(zip_name, 'w') as zipf:
        for file in files:
            zipf.write(file)
    print(f"{zip_name} created successfully.")

files_to_compress = ['file1.txt', 'file2.txt']
create_zip('example.zip', files_to_compress)

解释: 使用ZipFile对象的write方法添加文件到压缩包中。

技巧2: 压缩目录

目标: 将整个目录打包进ZIP文件。

def compress_directory(zip_name, directory):
    with zipfile.ZipFile(zip_name, 'w') as zipf:
        for root, dirs, files in os.walk(directory):
            for file in files:
                zipf.write(os.path.join(root, file))
    print(f"{zip_name} created successfully.")

compress_directory('directory.zip', 'my_directory')

注意: 需要先导入os模块。

技巧3: 解压ZIP文件

目标: 将ZIP文件解压到指定目录。

def extract_zip(zip_name, extract_to):
    with zipfile.ZipFile(zip_name, 'r') as zipf:
        zipf.extractall(extract_to)
    print(f"{zip_name} extracted successfully to {extract_to}.")

extract_zip('example.zip', 'extracted_files')

技巧4: 列出ZIP文件中的内容

目标: 查看ZIP文件内包含的文件列表。

def list_files_in_zip(zip_name):
    with zipfile.ZipFile(zip_name, 'r') as zipf:
        print("Files in ZIP:", zipf.namelist())

list_files_in_zip('example.zip')

技巧5: 使用TarFile创建.tar.gz压缩文件

目标: 创建一个gzip压缩的tar文件。

import tarfile

def create_tar_gz(tar_name, source_dir):
    with tarfile.open(tar_name, 'w:gz') as tar:
        tar.add(source_dir, arcname=os.path.basename(source_dir))
    print(f"{tar_name} created successfully.")

create_tar_gz('example.tar.gz', 'my_directory')

技巧6: 解压.tar.gz文件

目标: 解压.tar.gz文件到当前目录。

def extract_tar_gz(tar_name):
    with tarfile.open(tar_name, 'r:gz') as tar:
        tar.extractall()
    print(f"{tar_name} extracted successfully.")

extract_tar_gz('example.tar.gz')

技巧7: 压缩并加密ZIP文件

目标: 创建一个需要密码才能解压的ZIP文件。

from zipfile import ZIP_DEFLATED

def create_protected_zip(zip_name, files, password):
    with zipfile.ZipFile(zip_name, 'w', compression=ZIP_DEFLATED) as zipf:
        for file in files:
            zipf.write(file)
        zipf.setpassword(bytes(password, 'utf-8'))
    print(f"{zip_name} created successfully with password protection.")

password = "securepass"
create_protected_zip('protected_example.zip', files_to_compress, password)

技巧8: 解压加密的ZIP文件

目标: 解压需要密码的ZIP文件。

def extract_protected_zip(zip_name, password):
    with zipfile.ZipFile(zip_name, 'r') as zipf:
        zipf.setpassword(bytes(password, 'utf-8'))
        zipf.extractall()
    print(f"{zip_name} extracted successfully.")

extract_protected_zip('protected_example.zip', password)

技巧9: 分卷压缩ZIP文件

目标: 将大文件分割成多个ZIP分卷。

def split_large_file(zip_name, max_size=1024*1024):  # 1MB per part
    with zipfile.ZipFile(zip_name + ".part01.zip", 'w') as zipf:
        for i, filename in enumerate(files_to_compress, start=1):
            if zipf.getinfo(filename).file_size > max_size:
                raise ValueError("File too large to split.")
            zipf.write(filename)
            if zipf.filesize > max_size:
                zipf.close()
                new_part_num = i // max_size + 1
                zip_name_new = zip_name + f".part{new_part_num:02d}.zip"
                with zipfile.ZipFile(zip_name_new, 'w') as new_zipf:
                    new_zipf.comment = zipf.comment
                    for j in range(i):
                        new_zipf.write(zip_name + f".part{j+1:02d}.zip")
                    new_zipf.write(filename)
                break
    print(f"{zip_name} split into parts successfully.")

split_large_file('large_file.zip')

技巧10: 合并ZIP分卷

目标: 将ZIP分卷合并为一个文件。

def merge_zip_parts(zip_base_name):
    parts = sorted(glob.glob(zip_base_name + ".part*.zip"))
    with zipfile.ZipFile(zip_base_name + ".zip", 'w') as dest_zip:
        for part in parts:
            with zipfile.ZipFile(part, 'r') as src_zip:
                for item in src_zip.infolist():
                    dest_zip.writestr(item, src_zip.read(item))
    for part in parts:
        os.remove(part)
    print(f"Parts merged into {zip_base_name}.zip")

merge_zip_parts('large_file.zip')

技巧拓展

技巧拓展1: 自动处理压缩文件类型

在处理未知压缩类型时,可以利用第三方库如patool自动识别并操作压缩文件。

首先,安装patool

pip install patool

然后,编写通用的压缩和解压缩函数:

import patoolib

def compress_file(input_path, output_path, format=None):
    """Compress a file or directory."""
    patoolib.create_archive(output_path, [input_path], format=format)

def decompress_file(input_path, output_dir="."):
    """Decompress a file."""
    patoolib.extract_archive(input_path, outdir=output_dir)

这样,你可以不关心是.zip.tar.gz, 还是其他格式,函数会自动处理。

技巧拓展2: 实时监控文件夹并压缩新文件

使用watchdog库,我们可以创建一个脚本,实时监控指定文件夹,一旦有新文件添加,立即自动压缩。

首先安装watchdog:

pip install watchdog

然后,编写监控并压缩的脚本:

from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import time
import zipfile
import os

class MyHandler(FileSystemEventHandler):
    def on_created(self, event):
        if event.is_directory:
            return
        zip_name = os.path.splitext(event.src_path)[0] + '.zip'
        with zipfile.ZipFile(zip_name, 'w') as zipf:
            zipf.write(event.src_path)
            print(f"{event.src_path} has been compressed to {zip_name}")

if __name__ == "__main__":
    event_handler = MyHandler()
    observer = Observer()
    observer.schedule(event_handler, path='watched_directory', recursive=False)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

这个脚本持续运行,监视watched_directory,每当有文件被创建,就将其压缩。

技巧拓展3: 压缩优化与速度调整

在使用zipfile时,可以通过设置压缩级别来平衡压缩比和压缩速度。级别范围是0到9,0表示存储(不压缩),9表示最大压缩。

with zipfile.ZipFile('compressed.zip', 'w', zipfile.ZIP_DEFLATED, compresslevel=6) as zipf:
    zipf.write('file_to_compress.txt')

这里使用了6作为压缩级别,是一个常用的平衡点。

结语

通过上述技巧和拓展,你不仅掌握了Python处理文件压缩与解压的基础,还了解了如何在特定场景下提升效率和灵活性。

好了,今天的分享就到这里了,我们下期见。如果本文对你有帮助,请动动你可爱的小手指点赞、转发、在看吧!

文末福利

如果你对Python感兴趣的话,可以试试我整理的这一份全套的Python学习资料,【点击这里】免费领取!

包括:Python激活码+安装包、Python
web开发,Python爬虫,Python数据分析,人工智能、自动化办公等学习教程。带你从零基础系统性的学好Python!

① Python所有方向的学习路线图,清楚各个方向要学什么东西
② 100多节Python课程视频,涵盖必备基础、爬虫和数据分析
③ 100多个Python实战案例,学习不再是只会理论
④ 华为出品独家Python漫画教程,手机也能学习

可以微信扫描下方二维码名片免费获取【保证100%免费】

  • 9
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值