首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >用Python删除.json文件中的特定行?

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

Stack Overflow用户
提问于 2019-12-27 10:41:05
回答 2查看 1.1K关注 0票数 0

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

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

代码语言:javascript
运行
AI代码解释
复制
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) 

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

EN

回答 2

Stack Overflow用户

发布于 2019-12-27 10:47:14

你可以这样做:

代码语言:javascript
运行
AI代码解释
复制
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)

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

代码语言:javascript
运行
AI代码解释
复制
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))
票数 1
EN

Stack Overflow用户

发布于 2019-12-27 11:11:20

这个答案只适用于JSON文件,在这种情况下,这是一种健壮的工作方式:

代码语言:javascript
运行
AI代码解释
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59499522

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档