压缩和解压缩是日常常用的操作,不管是windows上图形界面的操作,还是linux上用命令来进行压缩解压缩,总的而言都还是比较方便的。
但用代码来实现就没做过,近期也得实现代码压缩与解压缩操作,所以就抽时间来研究一下。
二、zip文件压缩和解压缩实现
import os
import zipfile
def my_zip_function(zip_file_name, zip_file_list=[], zip_dir_list=[]):
with zipfile.ZipFile(zip_file_name, "w") as zip_obj:
for tmp_file in zip_file_list:
zip_obj.write(tmp_file)
for tmp_dir in zip_dir_list:
for root, dirs, files in os.walk(tmp_dir):
zip_obj.write(root)
for tmp_file in files:
tmp_file_path = os.path.join(root, tmp_file)
zip_obj.write(tmp_file_path)
def my_traversal_zip_function(zip_file_name):
with zipfile.ZipFile(zip_file_name, "r") as zip_obj:
all_file_list = zip_obj.infolist()
for tmp_file in all_file_list:
print(tmp_file.filename)
def my_unzip_function(zip_file_name, path="."):
with zipfile.ZipFile(zip_file_name, "r") as zip_obj:
zip_obj.extractall(path=path)
if __name__ == "__main__":
zip_file_name = "test_zip.zip"
zip_file_list = ["test_tar_file1.txt", "test_tar_file2.txt"]
zip_dir_list = ["test_tar_dir"]
my_zip_function(zip_file_name, zip_file_list, zip_dir_list)
my_traversal_zip_function(zip_file_name)
三、tar文件的压缩与解压缩实现
除了直接的.tar文件,还包括.tar.gz/.tar.bz2/.tar.xz等格式文件的压缩与解压缩实现。
import os
import tarfile
def my_tar_function(tar_file_name, tar_file_list=[], tar_dir_list=[], model="w"):
with tarfile.open(tar_file_name, model) as tar_obj:
for tmp_file in tar_file_list:
tar_obj.add(tmp_file)
for tmp_dir in tar_dir_list:
tar_obj.add(tmp_dir)
def my_traversal_tar_function(tar_file_name, model="r"):
with tarfile.open(tar_file_name, model) as tar_obj:
all_file_list = tar_obj.getmembers()
for tmp_file in all_file_list:
print(tmp_file.name)
def my_untar_function(tar_file_name, path=".", model="r"):
with tarfile.open(tar_file_name, model) as tar_obj:
tar_obj.extractall(path=path)
if __name__ == "__main__":
tar_file_list = ["test_tar_file1.txt", "test_tar_file2.txt"]
tar_dir_list = ["test_tar_dir"]
tar_file_name = "test_tar.tar"
open_model = "w"
my_tar_function(tar_file_name, tar_file_list, tar_dir_list, model=open_model)
open_model = "r"
my_traversal_tar_function(tar_file_name, model=open_model)
Python学习者
粉丝