python gzip模块实现文件压缩的方法

python gzip模块实现文件压缩的方法


使用gzip格式压缩文件,注意引入gzip包。

代码:
 

复制代码代码示例:

#!/bin/python
#
#site: www.jbxue.com
import string
import gzip
from optparse import OptionParser

def readCommandLine():
    parser = OptionParser()
    #read the options in
    parser.add_option("-f","--Full_file_location",
                    dest="File_to_be_run",
                    default=r"c:\tn.txt",
                    help="This is the fully qualified path name to the file location")

    parser.add_option("-m","--Mode",
                    dest="modeTn",
                    default="r",
                    help="The mode of zip unzip")

    parser.add_option("-c","--Compression",
                    dest="compress",
                    default=9,
                    help="The level of compression")
    options, args = parser.parse_args()
    #print options
    return options

def zipit(filename, mode,compress):
    #Saves/Zipps a compressed file to disk
    #
    r_file = open(filename, 'r')
    # this is the zipping bit
    w_file = gzip.GzipFile(filename + '.gz', mode, compress)
    w_file.write(r_file.read())
    w_file.flush()
    w_file.close()
    r_file.close()

def un_zipit(filename,mode):
    #Unzips a compressed file from disk
    #
    #this is the unzipping bit  
    r_file = gzip.GzipFile(filename, mode)
    write_file = string.rstrip(filename, '.gz')
    w_file = open(write_file, 'w')
    w_file.write(r_file.read())
    w_file.close()
    r_file.close()

if __name__ == "__main__":
    #first thing to do is read the options in
    options = readCommandLine()
    if options.modeTn == "r":
        #unzippit mode
        if options.File_to_be_run[-3:] != '.gz':
            # check to see if it has the extension .gz
            print "This " + options.File_to_be_run + " is not a .gz file"
        else:
            #This should now unzipit
            un_zipit(options.File_to_be_run,options.modeTn)
    elif options.modeTn== "wb":
            #this should zipit
            zipit(options.File_to_be_run,options.modeTn,options.compress)
    else:
        # basically the wrong option was passed
        print "ABORT something went wrong"
        sys.exit()


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值