python删除txt指定列_使用python删除json文件中指定的key值

问题:有1个文件t1.txt数据格式是json。

有另外1个文件t2.txt是key1111,key2222。把对应在t1.txt中的值删掉,有什么好办法么?

思路1:1条shell命令

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.txtsed '/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.html

#!/usr/bin/env python

importjsondefconvertDict():

with open('t1.txt') as json_file:

data=json.load(json_file)returndataif __name__ == "__main__":

fileToDict=convertDict()

keyList= ["key1111","key2222"]for k inkeyList: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()

#!/usr/bin/env python

importcommandsimportjsondefconvertDict():

outStr= commands.getoutput("cat t1.txt | python -m json.tool")

json_acceptable_string= outStr.replace("'", "\"")

toDict=json.loads(json_acceptable_string)printtype(toDict)printtoDictreturntoDictif __name__ == "__main__":

fileToDict=convertDict()

keyList= ["1111","2222"]for k inkeyList:del fileToDict["jobs"][k]print json.dumps(toDict)

3)# other ways for covert string to dictionay

#http://leaya00.iteye.com/blog/853366

#!/usr/bin/env python

importcommandsimportjsondefconvertDict():

outStr= commands.getoutput("cat t1.txt | python -m json.tool")

toDict=eval(outStr)#exec("toDict=" + outStr)

printtype(toDict)printtoDictreturntoDictif __name__ == "__main__":

fileToDict=convertDict()

keyList= ["1111","2222"]for k inkeyList: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来处理。

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.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值