`
这些年
  • 浏览: 389163 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

python 解压缩

阅读更多

一 python压缩解压libs

zlib:infozip免费的压缩lib。
bzip2:读写bz压缩文件,与bzip2和bunzip2压缩程序兼容。
gzip: 读写gz压缩文件,与GNU压缩程序gzip和gunzip兼容。
zipfile:读写zip压缩文件,与zip,unzip,pkzip,pkunzip,winzip等程序兼容。
tar:读写tar包文件。7z等程序可以大包和解包tar。

二:压缩zip文件并写入日志

import os
import zipfile


filename='c:/Temp.zip'
curdir="C:/Temp/"
os.chdir(curdir)

#Create the zip file
tFile = zipfile.ZipFile(filename, 'w')

#Write directory contents to the zip file
files = os.listdir(curdir)
for f in files:
    tFile.write(f)

#List archived files
for f in tFile.namelist():
    print ("Added %s" % f)

#close the zip file
tFile.close()

#whether the file is zip file
print(zipfile.is_zipfile(filename))

#list all file in the zip file
tFile = zipfile.ZipFile(filename, 'r')
for file in tFile.namelist():
    print(file)

#List info for archived file
tinfo=tFile.getinfo("test.log")
print(tinfo.comment)
print(tinfo.compress_size)
print(tinfo.date_time)
print(tinfo.file_size)
print(tinfo.compress_type)
print(tinfo.filename)

#Read zipped file into a buffer
buffer = tFile.read("test.log")
print (buffer)

#close the zip file
tFile.close()

 三:zip的目录压缩与解压

#coding=utf-8
#甄码农python代码
#使用zipfile做目录压缩,解压缩功能

import os,os.path
import zipfile

def zip_dir(dirname,zipfilename):
    filelist = []
    if os.path.isfile(dirname):
        filelist.append(dirname)
    else :
        for root, dirs, files in os.walk(dirname):
            for name in files:
                filelist.append(os.path.join(root, name))
        
    zf = zipfile.ZipFile(zipfilename, "w", zipfile.zlib.DEFLATED)
    for tar in filelist:
        arcname = tar[len(dirname):]
        #print arcname
        zf.write(tar,arcname)
    zf.close()


def unzip_file(zipfilename, unziptodir):
    if not os.path.exists(unziptodir): os.mkdir(unziptodir, 0777)
    zfobj = zipfile.ZipFile(zipfilename)
    for name in zfobj.namelist():
        name = name.replace('\\','/')
       
        if name.endswith('/'):
            os.mkdir(os.path.join(unziptodir, name))
        else:            
            ext_filename = os.path.join(unziptodir, name)
            ext_dir= os.path.dirname(ext_filename)
            if not os.path.exists(ext_dir) : os.mkdir(ext_dir,0777)
            outfile = open(ext_filename, 'wb')
            outfile.write(zfobj.read(name))
            outfile.close()

if __name__ == '__main__':
    zip_dir(r'c:/bbb',r'c:/aaa.zip')
    unzip_file(r'c:/aaa.zip',r'c:/bbb')

 四:gz文件压缩

import gzip

g = gzip.GzipFile(filename="", mode='wb', compresslevel=9, fileobj=open(r'c:\test.log.gz','wb'))
g.write(open(r'c:\Temp.zip').read())
g.close()

 五:gz 解压

import gzip

g = gzip.GzipFile(fileobj=open(r'c:\test.log.gz','rb'))
open(r'c:\Temp.zip','wb').write(g.read())

 注:

filename :为生成的压缩文件 r:\test.log.gz 内包含的文件的名称。如果为空这代表随压缩文件名称变化而变化。
fileobj :生成的压缩文件对象。
g.write(open(r’r:\test.log’).read()):打开被压缩的文件并写入压缩文件。

 官方help

zlib模块支持提供的数据压缩,兼容GNU压缩程序gzip。此外,gzip模块提供 GzipFile类读写gzip格式文件,自动压缩或解压缩数据,因此类似一个普通文件对象。注意,其他可以被gzip和gunzip解压缩的文件格式, 如由compress和pack产生的压缩文件,不被这个模块支持。
模块定义了如下条例:
class GzipFile([filename[, mode[, compresslevel[, fileobj]]]])
构造GzipFile类,类似大部分文件对象方法,有readinto()和trancate()方法异常,至少fileobj和filename必须为一个non-trivial的值。
基于fileobj产生的新类实例可以产生一个规则文件,一个StringIO对象,或任何类似文件的对象。默认是None,此处filename是产生一个文件对象。
当fileobj是None,filename只能使用包含压缩文件的原始文件的gzip文件头,默认fileobj文件是可识别的,其他,必须默认为空文本,同时原始文件名不比包含文件头。
mode可以为’r’,’rb’,’a’,’ab’,’w’或‘wb’,依赖文件是否被读或被写。默认可识别的fileobj模式:其他情况下默认是‘rb’,如果没有设定,‘b’标志将被添加到模式保证文件打开二进制模式交叉平台兼容。
压缩级别参数是一个从1到9的整数,控制压缩级别。1最快,最小压缩,9最慢,最大压缩,默认为9。
调用GzipFile对象close()方法不会关闭fileobj,由于你可能在压缩数据后添加更多材料。支持传递一个打开的StringIO对象作为fileobj,获取内存缓冲区结果使用StringIO对象的getvalue()方法。
open(filename[, mode[, compresslevel]])
GzipFile的速记方法(filename,mode,compresslevel),参数filename需要,mode默认为’rb’,压缩级别默认为9

 六:tar.gz文件压缩

import os

import tarfile

tar = tarfile.open("c:Temp.zip.tar.gz","w:gz")
for root,dir,files in os.walk("c:aaa"):
    for file in files:
        fullpath = os.path.join(root,file)
        tar.add(fullpath)  #这样会把文件及目录也打包

       #tar.add(fullpath,arcname=file)   #这样只会把文件把到包中
tar.close()

 七:tar.gz文件解压

import os

import tarfile

tar = tarfile.open("c:Temp.zip.tar.gz")
names = tar.getnames()
 
for name in names:
       tar.extract(name,path="c:bbb")
 
tar.close()

 注:

在打包的过程中可以设置压缩规则,如想要以gz压缩的格式打包
tar=tarfile.open('/path/to/your.tar.gz','w:gz')
其他格式如下表:
tarfile.open的mode有很多种:
mode action
'r' or 'r:*' Open for reading with transparent compression (recommended).
'r:' Open for reading exclusively without compression.
'r:gz' Open for reading with gzip compression.
'r:bz2' Open for reading with bzip2 compression.
'a' or 'a:' Open for appending with no compression. The file is created if it does not exist.
'w' or 'w:' Open for uncompressed writing.
'w:gz' Open for gzip compressed writing.
'w:bz2' Open for bzip2 compressed writing.

 八:使用md5为文件加密码生成tgz文件

import os
import shutil
import tarfile 
import time
from hashlib import md5
import logging   
import logging.config 

logging.config.fileConfig("logging.conf")
logger = logging.getLogger("tar")

def mv_source_file_to_temp(files,source_dir,temp_dir):
    for i in files:
        changeFilePath=os.path.join(source_dir,i);
        print changeFilePath
        shutil.move(changeFilePath,temp_dir); 

def tar_temp_file_to_objective(temp_dir,objective_temp_dir):
    filename=objective_temp_dir+'StatisticData_'+time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))+'_snp.tgz'
    tar = tarfile.open(filename,"w:gz")   
    for root,dir,files in os.walk(temp_dir):  
        global filelist ;
        filelist=files; 
        for file in files:   
            fullpath = os.path.join(root,file) 
            tar.add(fullpath,arcname='upload/'+file) #生成的tgz文件在upload目录下
            os.remove(os.path.join(temp_dir,file));  
    tar.close()
    return filename; 

def md5_file(name):
    m = md5()
    a_file = open(name, 'rb')
    m.update(a_file.read())
    a_file.close()
    return m.hexdigest()     


if __name__ == '__main__':
    source_dir='D:tmp/';          #源目录
    temp_dir='D:tar/temp/';       #源临时目录   
    objective_dir='D:';           #目标目录
    objective_temp_dir='D:tar/tar/temp/';   #tar文件临时目录
    file_group_size=10;           #每个tgz中的文件个数
    not_dispose_file_size=70;     #源目录个数小于时不处理
    if(not os.path.isdir(source_dir)):
        logger.error('source not filed');
        exit();
    elif(not os.path.isdir(temp_dir)):
        os.makedirs(temp_dir)
    elif(not os.path.isdir(objective_dir)):
        os.makedirs(objective_dir)
    elif(not os.path.isdir(objective_temp_dir)):
        os.makedirs(objective_temp_dir)
    elif(sum([len(files) for root,dirs,files in os.walk(source_dir)])<=not_dispose_file_size):
        logger.info('Don\'t deal with: log size '+str(sum([len(files) for root,dirs,files in os.walk(source_dir)]))); 
        exit();
    files=os.listdir(source_dir) ;
    file_group=[files[i:i+file_group_size] for i in xrange(0,len(files),file_group_size)];
    for f in file_group:
        mv_source_file_to_temp(f,source_dir,temp_dir);
        filename=tar_temp_file_to_objective(temp_dir,objective_temp_dir);
        md5_code=md5_file(filename);
        file_name=os.path.basename(filename).replace('snp', md5_code);
        logger.info(str(filelist)+' in '+file_name) ;
        shutil.move(filename, os.path.join(objective_dir, file_name ));

 日志配置文件

[loggers]
keys=root,simpleExample

[handlers]
keys=consoleHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler

[logger_simpleExample]
level=DEBUG
handlers=consoleHandler
qualname=simpleExample
propagate=0

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)

[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=

 解压

from hashlib import md5
import os
import re
import tarfile 
import logging   
import logging.config  

def md5_file(name):
    m = md5()
    a_file = open(name, 'rb')
    m.update(a_file.read())
    a_file.close()
    return m.hexdigest()
def nu_tar(source_file,Objective_dir):
	tar = tarfile.open(source_file)
	names = tar.getnames() 
	for name in names: 
		tar.extract(name,path=Objective_dir)
	tar.close() 
	
if __name__ == '__main__':
    tar_source='D:';
    file_Objective='D:';
    file_name_regular='tgz$';
    if(not os.path.isdir(tar_source)):
        logger.error('source not filed');
        exit();
    elif(not os.path.isdir(file_Objective)):
        os.makedirs(file_Objective)
    files=os.listdir(tar_source) ;
    file_list=[];
    [(re.search(file_name_regular,file) and file_list.append(file) or '') for file in files];
    for file_name in file_list:
    	md5code=md5_file(tar_source+file_name);
    	file_md5=file_name.split('_')[2];
    	if(re.search(md5code,file_md5)):
    		nu_tar(tar_source+file_name,file_Objective);  

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics