免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1459 | 回复: 0
打印 上一主题 下一主题

zip打包 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2013-03-26 18:09 |只看该作者 |倒序浏览
def ZipFiles(srcPath, zipFilename, arcName="/", CompressMode = 0):
    """
    Description: Zip all file in srcPath
    """

    tmpFile = None
    zipFile = None
    flag = None
    try:
        tmpFile = file(zipFilename,'wb')
        zipFile = zipfile.ZipFile(tmpFile,"w")
        flag = __addToZip(srcPath, zipFile, arcName, CompressMode )
    finally:
        if zipFile:
            zipFile.close()
        if tmpFile:
            tmpFile.close()

    if not flag:
        return False
    return True


def __addToZip(srcPath, zipFile, arcName, CompressMode = 0):
    """
    Description: Zip all file in srcPath
    """

    #add file into zip file
    if not os.path.isdir(srcPath):
        if arcName == "":
            fileName = os.path.basename(srcPath)
            arcName = fileName
        zipFile.write(srcPath, arcName, CompressMode)
        return True

    #add directory into zip file

    fileList = os.listdir(srcPath)
    if arcName == "":
        dirName = os.path.basename(srcPath)
        arcName = dirName + '/'
    if arcName == '/':
        arcName = ''
    else:
        zipFile.writestr(arcName, "")


    for fileName in fileList:
        filePath = os.path.join(srcPath, fileName)

        if os.path.isdir(filePath):
            if not __addToZip(filePath, zipFile,
                              arcName + fileName + '/', CompressMode):
                return False
        else:
            if len(filePath) > 255:
                print "zip %s path is more than 255 characters"%filePath
                return False
            zipFile.write(filePath, arcName + fileName, CompressMode)
    return True
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP