因为有些通用的资源需要使用代码更换,当时为了方便就简单的使用了python脚本语言进行操作,写了第一个个版本读取文本文件中的内容写入到其他的utf-8的格式的文件中,在python的头部加入下面代码在python头部即可
# coding:utf-8
但是后来觉得txt文本中的内容可读性太差,使用了json文件的格式。使用python读取json(utf-8格式)中的内容,替换其他java或者是xml中文件,python代码如下:
import json
import os,sys
path=sys.path[0]
print "path="+path
print path+"\\resources\\config.json"
f = file(path+"\\resources\\config.json")
s = json.load(f)
appname = s["appName"]
with open('C:/project/android/Test/strings.xml', 'r') as r:
lines = r.readlines()
with open('C:/project/android/Test/strings.xml', 'w') as w:
for l in lines:
w.write(l.replace('测试文字', appname))
json如下:
{"appName":"test"}
这种编码执行以后会报错
nicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in range(128)
直观的看就是ascii码在解码的时候出了错,所以我读读取json中的字段appname的字符串编码应该是不对的,不是uft-8的模式,所以我们需要给这个变量重新编码才能使用。于是在python中就关键代码可以如下实现:
with open('C:/project/android/Test/strings.xml', 'w') as w:
for l in lines:
w.write(l.replace('测试文字',appname.encode('utf-8')))
这样即可成功替换掉各种utf-8的文件中的需要替换的字符串。
提供一个python替换字符串的方法,只需调用即可replace(文件路径,需要被替换的字符串,新的字符串):
def replace(file_path, old_str, new_str):
try:
f = open(file_path,'r+')
all_lines = f.readlines()
f.seek(0)
f.truncate()
for line in all_lines:
line = line.replace(old_str, new_str)
f.write(line)
f.close()
except Exception,e:
print e
欢迎拍砖交流