使用Python从.json文件中删除特定行?

时间:2019-12-27 10:41:04

标签: python

这是一个问题,我可以从文件夹中删除行,但不能选择它们作为它们的相似方式。

例如,我有一个包含3000行等的.json文件,我需要删除以"navig"开头的行。我们如何修改Python代码?

with open("yourfile.txt", "r") as f:
    lines = f.readlines()

with open("yourfile.txt", "w") as f:    
    for line in lines:
        if line.strip("\n") != "nickname_to_delete":
            f.write(line) 

(该代码来自另一个答案。)

1 个答案:

答案 0 :(得分:0)

此答案仅适用于JSON文件,在这种情况下,这是完成工作的一种可靠方法:

import json

with open('yourJsonFile', 'r') as jf:
    jsonFile = json.load(jf)

print('Length of JSON object before cleaning: ', len(jsonFile.keys()))

testJson = {}
keyList = jsonFile.keys()
for key in keyList:
    if not key.startswith('SOMETEXT'):
        print(key)
        testJson[key] = jsonFile[key]

print('Length of JSON object after cleaning: ', len(testJson.keys()))

with open('cleanedJson', 'w') as jf:
    json.dump(testJson, jf)