设为首页 收藏本站
查看: 720|回复: 0

[经验分享] Python压缩文件

[复制链接]

尚未签到

发表于 2017-4-23 07:37:45 | 显示全部楼层 |阅读模式
python处理zip文件
有时我们需要在 Python 中使用 zip 文件,而在1.6版中,Python 就已经提供了 zipfile 模块可以进行这样的操作。不过 Python 中的 zipfile 模块不能处理多卷的情况,不过这种情况并不多见,因此在通常情况下已经足够使用了。下面我只是对一些基本的 zipfile 操作进行了记录,足以应付大部分的情况了。
zipfile 模块可以让你打开或写入一个 zip 文件。比如:
import zipfile
z = zipfile.ZipFile('zipfilename', mode='r')
这样就打开了一个 zip 文件,如果mode为'w'或'a'则表示要写入一个 zip 文件。如果是写入,则还可以跟上第三个参数:
compression=zipfile.ZIP_DEFLATED

compression=zipfile.ZIP_STORED
ZIP_DEFLATED是压缩标志,如果使用它需要编译了zlib模块。而后一个只是用zip进行打包,并不压缩。
在打开了zip文件之后就可以根据需要是读出zip文件的内容还是将内容保存到 zip 文件中。
读出zip中的内容
很简单,zipfile 对象提供了一个read(name)的方法。name为zip文件中的一个文件入口,执行完成之后,将返回读出的内容,你把它保存到想到的文件中即可。
写入zip文件
有两种方式,一种是直接写入一个已经存在的文件,另一种是写入一个字符串。
对于第一种使用 zipfile 对象的 write(filename, arcname, compress_type),后两个参数是可以忽略的。第一个参数是文件名,第二个参数是表示在 zip 文件中的名字,如果没有给出,表示使用与filename一样的名字。compress_type是压缩标志,它可以覆盖创建 zipfile 时的参数。第二种是使用 zipfile 对象的 writestr(zinfo_or_arcname, bytes),第一个参数是 zipinfo 对象或写到压缩文件中的压缩名,第二个参数是字符串。使用这个方法可以动态的组织文件的内容。
需要注意的是在读出时,因为只能读出内容,因此如果想实现按目录结构展开 zip 文件的话,这些操作需要自已来完成,比如创建目录,创建文件并写入。而写入时,则可以根据需要动态组织在 zip 文件中的目录结构,这样可以不按照原来的目录结构来生成 zip 文件。
于是我为了方便使用,创建了自已的一个 ZFile 类,主要是实现象 winrar 的右键菜单中的压缩到的功能--即将一个zip文件压缩到指定目录,自动创建相应的子目录。再有就是方便生成 zip 文件。类源码为:
import zipfile
import os.path
import os
class ZFile(object):
    def __init__(self, filename, mode='r', basedir=''):
        self.filename = filename
        self.mode = mode
        if self.mode in ('w', 'a'):
            self.zfile = zipfile.ZipFile(filename, self.mode, compression=zipfile.ZIP_DEFLATED)
        else:
            self.zfile = zipfile.ZipFile(filename, self.mode)
        self.basedir = basedir
        if not self.basedir:
            self.basedir = os.path.dirname(filename)
        
    def addfile(self, path, arcname=None):
        path = path.replace('\\', '/')
        if not arcname:
            if path.startswith(self.basedir):
                arcname = path[len(self.basedir):]
            else:
                arcname = ''
        self.zfile.write(path, arcname)
            
    def addfiles(self, paths):
        for path in paths:
            if isinstance(path, tuple):
                self.addfile(*path)
            else:
                self.addfile(path)
            
    def close(self):
        self.zfile.close()
        
    def extract_to(self, path):
        for p in self.zfile.namelist():
            self.extract(p, path)
            
    def extract(self, filename, path):
        if not filename.endswith('/'):
            f = os.path.join(path, filename)
            dir = os.path.dirname(f)
            if not os.path.exists(dir):
                os.makedirs(dir)
            file(f, 'wb').write(self.zfile.read(filename))
            
        
def create(zfile, files):
    z = ZFile(zfile, 'w')
    z.addfiles(files)
    z.close()
   
def extract(zfile, path):
    z = ZFile(zfile)
    z.extract_to(path)
    z.close()
这个 zfile.py 模块提供了两个方法:create和extract,还有一个 ZFile 的类。create和extract用来创建和解压 zip 文件。
create需要两个参数,第一个为要生成的zip文件名,第二个为一个文件列表,它是一个list变量,每一项或者是一个字符串文件名,或者是一个tuple,第一个为文件名,第二个为在压缩文件中的名字,可以有路径,如:
['d:/a.csv', 'd:/test/a.JPG', ('d:/test/mixin/main.py', 'main.py')]
那么对于文件名有以下的处理,如果文件列表中的文件名与压缩文件名的路径相同,则在压缩文件中会自动变成相对路径。比如上面的文件列表,如果压缩文件为:
d:/aaaa.zip
则在压缩文件中的压缩文件名最终为:
['a.csv', 'test/a.JPG', 'main.py']
那么最后一个因为指定了在压缩文件中的名字,因此使用指定的名字。
extrace需要两个参数,第一个为压缩文件名,第二个为解压到的路径名。
这两个方法都使用了 ZFile 类。ZFile 类则提供了一些更底层些的类。它的构造函数可以根据mode的值来选择是打开还是写入。另外如果还想做更底层的控制,可以通过 ZFile 实例得到 zfile 属性,它是一个 ZipFile 模块实例,可以直接使用。






(windows)python脚本:自动备份并压缩文件,同时删除过期文件



       近来忙东忙西,有些重复性的事务就懒得做,比如文件备份。不过不做也不行。这两天闲下来,现学现用python写了这个文件自动备份的脚本。

        有以下2个亮点:

1.可以放在计划任务中定期执行,所需备份的内容由dsvr1list.txt文件提供,备份文件自动备份到按当前日期生成的目录中。

2.程序刚开始就执行清除1个月以前的所有备份目录,这个功能对于只有特定大小的备份设备及其有用,从此文件备份完全不用人工干涉。

      代码很简单,该注释的我都注释了。需要注意的是,我安装的的是python 2.5.1,是否对其他版本的python兼容有待考查;压缩格式我选用7-zip,其中7z.exe是它的命令行程序,该软件为开源软件,并且压缩比应该算是同类软件中最高的。(经过我的测试,备份文件服务器上2.4G左右的东西,压缩后只剩不到900M)如果第一次安装python环境和7-zip软件,请为它们设置path变量,因为我的脚本里面假定它们可以在任何目录下执行。

#!/usr/bin/python
# Filename: bDatasvr1.py
# This program is for files backup only
# It also needs 7-zip as the compress tool.
# Tengda huang, Dec 17th, 2007
# ver 1.0

import os
import time
import distutils.dir_util
import datetime

# connecting to the remote computer
link_command = r"net use k: \\10.10.10.1\mysvr1 mypassword /user:backupUser"

print 'Connecting to remote computer'

if os.system(link_command) == 0:
    print 'Successful connecting to drive k !'
else:
    print 'Drive k already linked or link failed!'

# delete old directories and files if the dir name created by time is older than 30 days
for root, dirs, files in os.walk('k:'):
    for name in dirs:
        (y1, m1, d1) = (int(x) for x in name.split('-'))
        date1 = datetime.date(y1, m1, d1)
        datenow = time.strftime('%Y%m%d')
        y2 = int(datenow[:4])
        m2 = int(datenow[4:6])
        d2 = int(datenow[6:])
        date2 = datetime.date(y2, m2, d2)
        if (date2 - date1).days > 30:
            print 'Expired dir! Deleting directory... ', name
            distutils.dir_util.remove_tree(os.path.join("k:",name))
print 'Old directory deleting done!'
print 'Starting to create backup files!'

# 1. The files and directories to be backed up are specified in the list.
source = r'@dsvr1list.txt'

# 2. The backup must be stored in a main directory,
#    that is  \\10.10.10.1mysvr1
#    which mapped as drive k:
target_dir = 'k:'  

# 3. The files are compressed and backed up into a 7-zip file type.
#    The subdirectories are named by the current day time.
today = target_dir + time.strftime('%Y-%m-%d')

# The current time is the name of the zip archive
now = time.strftime('%H%M%S')

# Create the subdirectory if it isn't already there
if not os.path.exists(today):
    os.mkdir(today) # make directory
    print 'Successfully created directory', today

# The name of the zip file
target = today + os.sep + 'share' + now + '.7z'

# 5. Use the 7z command to compress and put the files in a 7z archive
zip_command = "7z a -t7z %s %s" % (target, source)

# Runing the backup
if os.system(zip_command) == 0:
    print 'Successful backup to', target
else:
    print 'Backup FAILED'

# Disconnect from the remote computer
unlink_command = r"net use k: /delete"

if os.system(unlink_command) == 0:
    print 'Successfully detach from drive k! '
    print 'All job done!'
else:
    print 'Backup FAILED'


使用python压缩文件为zip压缩包
python自带了zipfile,貌似支持ZIP64,看帮助文档里好像有个选项
今天我的工作只是备份,所以只是创建zip档,其他就不关心了 ……
#!/usr/bin/env python
#coding=gbk
# python[AT]Live.it
import os
import sys
import getopt
import string
import zipfile

# print Help message
def Help():
    print "Usage : python %s -t D:\\dir -z test.zip" %sys.argv[0]
    sys.exit(0)
# get options
try:
    opts , args = getopt.getopt(sys.argv[1:], "ht:z:")
except getopt.GetoptError:
    print "\tBad arguments !"
    Help()
# enum options
if 0 == len(opts):
    Help()
for o,v in opts:
    if ‘-h‘ == o.lower():
        Help()
    if ‘-t‘ == o.lower():
        target = v
    if ‘-z‘ == o.lower():
        zipname = v
# zip directory
def zipDirectory(dir):
    dir = dir.strip()
    for (root,dirs,files) in os.walk(dir):
        for filename in files:
            print "Zip : %s" %(root+os.sep+filename)
            z.write(root+os.sep+filename)
    z.close()
# zip single file
def zipSingleFile(singleFile):
    print "Zip : %s" %singleFile
    singleFile = singleFile.strip()
    z.write(singleFile )
    z.close()
# run it
if os.path.isdir(target):
    z = zipfile.ZipFile(zipname,‘w‘)
    zipDirectory(target)
if os.path.isfile(target):
    z = zipfile.ZipFile(zipname,‘w‘)
    zipSingleFile(target)
run it
D:\>python zip.py -t D:\WIR -z E:\wir.zip
Zip : D:\WIR\Clip.py
Zip : D:\WIR\getClip.pl
Zip : D:\WIR\getClip.py
Zip : D:\WIR\openfiles.bmp
Zip : D:\WIR\Thumbs.db
Zip : D:\WIR\01\logosessions.png
Zip : D:\WIR\01\netsession.png
Zip : D:\WIR\01\netstat.png
Zip : D:\WIR\01\psloggedon.png
Zip : D:\WIR\01\tcpvcon.png
Zip : D:\WIR\01\wir
D:\>ls E:\wir.zip
E:\wir.zip

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-367951-1-1.html 上篇帖子: python mongodb测试 下篇帖子: Python 简洁学习
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表