# coding=utf8
#替换模板中的survey_id
import os,sys
import json
#服务器1的数据
rSimple = ''
rEvent = ''
rDriving = ''
rFutures = ''
vText = ''
vPic = ''
vOscar = ''
vRunningman = ''
zCampus = ''
zVolunteer = ''
zEnterprise = ''
eRecruit = ''
eRegisteration = ''
eVote = ''
#服务器2的数据
rSimpleNew = ''
rEventNew = ''
rDrivingNew = ''
rFuturesNew = ''
vTextNew = ''
vPicNew = ''
vOscarNew = ''
vRunningmanNew = ''
zCampusNew = ''
zVolunteerNew = ''
zEnterpriseNew = ''
eRecruitNew = ''
eRegisterationNew = ''
eVoteNew = ''
#服务器3的数据
rSimpleNew2 = ''
rEventNew2 = ''
rDrivingNew2 = ''
rFuturesNew2 = ''
vTextNew2 = ''
vPicNew2 = ''
vOscarNew2 = ''
vRunningmanNew2 = ''
zCampusNew2 = ''
zVolunteerNew2 = ''
zEnterpriseNew2 = ''
eRecruitNew2 = ''
eRegisterationNew2 = ''
eVoteNew2 = ''
# 格式: key是模板中的title, value 依次是 服务器1的数据、服务器2的数据、服务器3的数据
surveyIdDics = {u'简单报名表':[rSimple,rSimpleNew, rSimpleNew2],
u'活动报名':[rEvent, rEventNew, rEventNew2],
u'预约试驾':[rDriving, rDrivingNew, rDrivingNew2],
u'商品预购':[rFutures, rFuturesNew, rFuturesNew2],
u'文字投票':[vText, vTextNew, vTextNew2],
u'图片投票':[vPic, vPicNew, vPicNew2],
u'人物评选':[vOscar, vOscarNew, vOscarNew2],
u'奔跑吧兄弟':[vRunningman,vRunningmanNew,vRunningmanNew2],
u'校园招聘':[zCampus,zCampusNew,zCampusNew2],
u'志愿者招募':[zVolunteer,zVolunteerNew,zVolunteerNew2],
u'名企招聘':[zEnterprise,zEnterpriseNew,zEnterpriseNew2],
u'招聘页':[eRecruit,eRecruitNew,eRecruitNew2],
u'报名页':[eRegisteration,eRegisterationNew,eRegisterationNew2],
u'投票页':[eVote,eVoteNew,eVoteNew2]}
def replace(f):
if not os.path.exists(f):
exit(-1)
#读
fpr = open(f, 'r')
dict = json.loads(fpr.read())
fpr.close()
#修改
title = dict["title"]
surveyIdArray = surveyIdDics.get(title, None)
if surveyIdArray is not None:
surveyIdOrigin = surveyIdArray[0]
surveyIdNew = surveyIdArray[1]
surveyIdNew2 = surveyIdArray[2]
#写
lines = open(f).readlines()
newFile = os.path.join(newDir,f)
newFile2 = os.path.join(newDir2,f)
fpw = open(newFile,'w')
fpw2 = open(newFile2,'w')
for s in lines:
fpw.write(s.replace(surveyIdOrigin,surveyIdNew)) # replace是替换,write是写入
fpw2.write(s.replace(surveyIdOrigin,surveyIdNew2)) # replace是替换,write是写入
fpw.close() # 关闭文件
fpw2.close();
'''
# 写入json文件
newFile = os.path.join(newDir,f)
fpw = open(newFile,'w')
fpw.write(json.loads(dict))
fpw.close()
'''
def createNewDir(dir):
isExist = os.path.exists(dir)
if not isExist:
# print "dir not exist. create dir: " + dir
os.mkdir(dir)
# else:
# print "dir exist: " + dir
dir = sys.path[0]
#print dir
newDir = sys.path[0] + "/test.wenjuan.it/"
createNewDir(newDir)
newDir2 = sys.path[0] + "/wenjuan.com/"
createNewDir(newDir2)
for f in os.listdir(dir):
if (os.path.isfile(f)) and os.path.splitext(f)[1] == '.json':
print 'dealing file: ' + f
replace(f)
Python脚本10 —— 复制json文件并替换指定字段
最新推荐文章于 2024-10-13 15:20:58 发布