十個(gè) Python文件壓縮與解壓實(shí)戰(zhàn)技巧
在日常開發(fā)和數(shù)據(jù)處理中,文件的壓縮與解壓是一項(xiàng)基礎(chǔ)而實(shí)用的技能。Python通過zipfile和tarfile模塊提供了強(qiáng)大的文件壓縮和解壓縮功能。下面,我們將通過10個(gè)實(shí)戰(zhàn)技巧,一步步深入學(xué)習(xí)如何高效地操作文件壓縮包。
技巧1: 創(chuàng)建ZIP壓縮文件
目標(biāo): 將多個(gè)文件或目錄打包成一個(gè)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對(duì)象的write方法添加文件到壓縮包中。
技巧2: 壓縮目錄
目標(biāo): 將整個(gè)目錄打包進(jìn)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')
注意: 需要先導(dǎo)入os模塊。
技巧3: 解壓ZIP文件
目標(biāo): 將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文件中的內(nèi)容
目標(biāo): 查看ZIP文件內(nèi)包含的文件列表。
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創(chuàng)建.tar.gz壓縮文件
目標(biāo): 創(chuàng)建一個(gè)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文件
目標(biāo): 解壓.tar.gz文件到當(dāng)前目錄。
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文件
目標(biāo): 創(chuàng)建一個(gè)需要密碼才能解壓的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文件
目標(biāo): 解壓需要密碼的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文件
目標(biāo): 將大文件分割成多個(gè)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分卷
目標(biāo): 將ZIP分卷合并為一個(gè)文件。
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: 自動(dòng)處理壓縮文件類型
在處理未知壓縮類型時(shí),可以利用第三方庫如patool自動(dòng)識(shí)別并操作壓縮文件。
首先,安裝patool:
pip install patool
然后,編寫通用的壓縮和解壓縮函數(shù):
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)
這樣,你可以不關(guān)心是.zip, .tar.gz, 還是其他格式,函數(shù)會(huì)自動(dòng)處理。
技巧拓展2: 實(shí)時(shí)監(jiān)控文件夾并壓縮新文件
使用watchdog庫,我們可以創(chuàng)建一個(gè)腳本,實(shí)時(shí)監(jiān)控指定文件夾,一旦有新文件添加,立即自動(dòng)壓縮。
首先安裝watchdog:
pip install watchdog
然后,編寫監(jiān)控并壓縮的腳本:
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()
這個(gè)腳本持續(xù)運(yùn)行,監(jiān)視watched_directory,每當(dāng)有文件被創(chuàng)建,就將其壓縮。
技巧拓展3: 壓縮優(yōu)化與速度調(diào)整
在使用zipfile時(shí),可以通過設(shè)置壓縮級(jí)別來平衡壓縮比和壓縮速度。級(jí)別范圍是0到9,0表示存儲(chǔ)(不壓縮),9表示最大壓縮。
with zipfile.ZipFile('compressed.zip', 'w', zipfile.ZIP_DEFLATED, compresslevel=6) as zipf:
zipf.write('file_to_compress.txt')
這里使用了6作為壓縮級(jí)別,是一個(gè)常用的平衡點(diǎn)。
結(jié)語
通過上述技巧和拓展,你不僅掌握了Python處理文件壓縮與解壓的基礎(chǔ),還了解了如何在特定場景下提升效率和靈活性。