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

2024-06-16 12:34:36 发布

您现在位置: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) 

(代码取自另一个答案。)


Tags: 文件代码txt文件夹jsonforaswith
2条回答

你可以这样做:

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

with open("yourfile.txt", "w") as f:    
    for line in lines:
        if not line.startswith(YOUR_SEARCH_STRING):
            f.write(line)

或者如果只想写一次文件:

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

lines_to_write = [line for line in lines if not line.startswith(YOUR_SEARCH_SRING)]

with open("yourfile.txt", "w") as f:    
    f.write(''.join(lines_to_write))

这个答案只适用于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)

相关问题 更多 >