問題:有1個文件t1.txt數據格式是json。
有另外1個文件t2.txt是key1111,key2222。把對應在t1.txt中的值刪掉,有什麼好辦法麼?html
思路1:1條shell命令python
cat t1.txt | python -c 'import sys,json; a=json.load(sys.stdin);del a["jobs"]["1111"];del a["jobs"]["2222"];print a'
cat t1.txt | python -m json.tool >> t2.txt sed '/1111\|2222/,+3d' t2.txt
思路2:用python腳本刪,把t1賦給1個字典型的變量,把t2給一個list變量,循環讀取變量元素做爲key,直接刪除t1對應的值。
主要是string轉換爲dict或者json文件直接轉換爲dict。
1)# 使用json模塊直接把文件轉換爲字典值。
#https://docs.python.org/3/library/json.htmllinux
#!/usr/bin/env python import json def convertDict(): with open('t1.txt') as json_file: data = json.load(json_file) return data if __name__ == "__main__": fileToDict = convertDict() keyList = ["key1111","key2222"] for k in keyList: del fileToDict["jobs"][k] print json.dumps(fileToDict)
2)# 由於這是個linux下的配置文件,可使用commands模塊call shell command取值。
#http://stackoverflow.com/questions/988228/convert-a-string-representation-of-a-dictionary-to-a-dictionary
#convert string to dictionay by
#ast.literal_eval or json.loads()shell
#!/usr/bin/env python import commands import json def convertDict(): outStr = commands.getoutput("cat t1.txt | python -m json.tool") json_acceptable_string = outStr.replace("'", "\"") toDict = json.loads(json_acceptable_string) print type(toDict) print toDict return toDict if __name__ == "__main__": fileToDict = convertDict() keyList = ["1111","2222"] for k in keyList: del fileToDict["jobs"][k] print json.dumps(toDict)
3)# other ways for covert string to dictionayjson
#http://leaya00.iteye.com/blog/853366
spa
#!/usr/bin/env python import commands import json def convertDict(): outStr = commands.getoutput("cat t1.txt | python -m json.tool") toDict = eval(outStr) #exec("toDict=" + outStr) print type(toDict) print toDict return toDict if __name__ == "__main__": fileToDict = convertDict() keyList = ["1111","2222"] for k in keyList: del fileToDict["jobs"][k] print json.dumps(fileToDict)
4)遇到的錯誤TypeError: string indices must be integers, not str
http://stackoverflow.com/questions/15388980/typeerror-string-indices-must-be-integers-not-str
主要是使用commands.getoutput()獲取shell命令的輸出值是個string,不能直接看成dict來處理。.net
5)一些基礎的python知識參考
http://www.runoob.com/python/python-dictionary.html
http://www.jb51.net/article/47978.htm list
http://www.jb51.net/article/47990.htm dictionary
https://docs.python.org/3/library/json.html3d