python27 压缩 json 文件

62 阅读1分钟
#!/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