时间:2021-07-01 10:21:17 帮助过:49人阅读
服务端的json文件都是人工写的,写完之后发现格式都是十分规整,易于人阅读的json,但是客户端请求不需要那些为了格式而在json里面添加的空格、tab、回车等等没用的字符,遂用python写一脚本,去除文件中的空格、回车、换行。
原json文件:
{ "amount" : "2", "content" : [ { "category_id" : 0, "name" : "古典文学", "category_json_url" : "http://172.16.242.14:8080/source/history/history.json" }, { "category_id" : 1, "name" : "流行音乐", "category_json_url" : "http://172.16.242.14:8080/source//popmusic/popmusic.json" } ] }
用脚本处理后的文件:
{"amount":"2","content":[{"category_id":0,"name":"古典文学","category_json_url":"http://172.16.242.14:8080/source/history/history.json"},{"category_id":1,"name":"流行音乐","category_json_url":"http://172.16.242.14:8080/source//popmusic/popmusic.json"}]}
下面上代码:
def stripFile(oldFName,newFName): '''''remove the space or Tab or enter in a file,and output to a new file in the same folder''' fp = open(oldFName,"r+") newFp = open(newFName,"w") for eachline in fp.readlines(): newStr = eachline.replace(" ","").replace("\t","").strip() #print "Write:",newStr newFp.write(newStr) fp.close() newFp.close() if __name__ == "__main__": oldName = raw_input("input file name:") nameList = oldName.split(".") newName = "%s%s%s" % (nameList[0],"_new.",nameList[1]) stripFile(oldName,newName) print "finish output to new file:",newName
使用脚本时,如果脚本文件和要处理的文件在同一目录下,则直接输入文件名,如果不在,需要输入文件的完整路径。
以上就是如何截掉空格(包括tab)的详细内容,更多请关注Gxl网其它相关文章!