#一次性打包整个根目录。空子目录会被打包。 #如果只打包不压缩,将"w:gz"参数改为"w:"或"w"即可。 def make_targz(output_filename, source_dir): with tarfile.open(output_filename, "w:gz") as tar: tar.add(source_dir, arcname=os.path.basename(source_dir)) #逐个添加文件打包,未打包空子目录。可过滤文件。 #如果只打包不压缩,将"w:gz"参数改为"w:"或"w"即可。 def make_targz_one_by_one(output_filename, source_dir): tar = tarfile.open(output_filename,"w:gz") for root,dir,files in os.walk(source_dir): for file in files: pathfile = os.path.join(root, file) tar.add(pathfile) tar.close() make_targz('test.tar.gz',"E:\python_sample\libs") make_targz_one_by_one('test01.tgz',"E:\python_sample\libs")
import gzip
import os
def un_gz(file_name):
    """ungz zip file"""
    f_name = file_name.replace(".gz", "")
    #获取文件的名称,去掉
    g_file = gzip.GzipFile(file_name)
    #创建gzip对象
    open(f_name, "wb+").write(g_file.read())
    #gzip对象用read()打开后,写入open()建立的文件里。
    g_file.close() #关闭gzip对象
import tarfile
def un_tar(file_name):
    #untar zip file
    tar = tarfile.open(file_name)
    names = tar.getnames()
    if os.path.isdir(file_name + "_files"):
    else:
        os.mkdir(file_name + "_files")
    #由于解压后是许多文件,预先建立同名文件夹
    for name in names:
        tar.extract(name, file_name + "_files/")
    tar.close()
un_gz("test.tar.gz")
un_tar("test.tar")
import os, zipfile
#打包目录为zip文件(未压缩)
def make_zip(source_dir, output_filename):
    zipf = zipfile.ZipFile(output_filename, 'w')
    pre_len = len(os.path.dirname(source_dir))
    for parent, dirnames, filenames in os.walk(source_dir):
        for filename in filenames:
            print(filename)
            pathfile = os.path.join(parent, filename)
            arcname = pathfile[pre_len:].strip(os.path.sep)   #相对路径
            zipf.write(pathfile, arcname)
        print()
    zipf.close()
make_zip(r"E:\python_sample\libs\test_tar_files\libs","test.zip")
import os,zipfile
def un_zip(file_name):
    """unzip zip file"""
    zip_file = zipfile.ZipFile(file_name)
    if os.path.isdir(file_name + "_files"):
    else:
        os.mkdir(file_name + "_files")
    for names in zip_file.namelist():
        zip_file.extract(names,file_name + "_files/")
    zip_file.close()
un_zip("test.zip")
#rarfile不支持创建rar压缩卷,请用zip/7z
import rarfile
def unrar(rar_file, dir_name):
# rarfile需要unrar支持,
# linux下pip install unrar, windows下在winrar文件夹找到unrar,加到path里
rarobj = rarfile.RarFile(rar_file.decode('utf-8'))
rarobj.extractall(dir_name.decode('utf-8'))