python27 压缩 json

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import os.path
import re

def moveFile(infile, outfile):
    inBuffer = ""
    with open(infile, "rb+") as fr:
        inBuffer = fr.read()
    with open(outfile, "wb+") as fw:
        fw.write(inBuffer)

# 压缩
def zipFile(infile, outfile):
    inBuffer = ''
    outBuffer = ''

    with open(infile, 'rb+') as fr:
        inBuffer = fr.read()

    outBuffer = inBuffer.replace("\r\n", '')
    
    outBuffer = re.sub(re.compile(r'\{\s+'), '{', outBuffer)
    outBuffer = re.sub(re.compile(r'\[\s+'), '[', outBuffer)
    outBuffer = re.sub(re.compile(r'\s+\}'), '}', outBuffer)
    outBuffer = re.sub(re.compile(r',\s+'), ',', outBuffer)
    outBuffer = re.sub(re.compile(r':\s'), ':', outBuffer)

    with open(outfile,'wb+') as fw:
        fw.write(outBuffer)

    print infile, 'zip done '


# 压缩路径下文件
def encodeDir(rootdir, outDir):
    for parent,dirnames,filenames in os.walk(rootdir):
        if len(filenames) > 0:
            for filename in filenames:
                files = filename.partition(".")
                inPath=os.path.join(parent,filename)
                outDir2 = outDir+parent.replace(rootdir, "")
                if not os.path.exists(outDir2):
                    os.makedirs(outDir2)
                outPath=os.path.join(outDir2, filename)
                if len(files) > 2:
                    if files[len(files)-1] == "json":
                        zipFile(inPath, outPath)
                    else:
                        moveFile(inPath, outPath)


if len(sys.argv) != 3:
    if len(sys.argv) < 2:
        print('please input import folder ')
    elif len(sys.argv) < 3:
        print('please input export folder ')
else:
    encodeDir(sys.argv[1], sys.argv[2])

压缩效果:

image.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容