首页 > 解决方案 > 在python中开始没有按预期返回

问题描述

我有一个名为的 json 文件response

{

    "id": "163698b3-1e6b-4087-b398-16e2f5b1e7ef",

    "status": "Submitted"

  },

  {

    "id": "ed433b9e-ea4e-4652-907e-03114f869774",

    "status": "Submitted"

  },

  {

    "id": "3cd662fb-afdd-47e1-abde-364d727cfdab",

    "status": "Submitted"

  }

我搜索以 开头的行status

search = '"status"'

with open('path/to/file') as response:
    for line in response:
        if line.startswith(search):
            print(line)

而且我没有输出,这是为什么呢?我的最终目标是删除这条线。谢谢。

标签: python

解决方案


代码:</p>

search = '"status"'
with open("test.json", "r") as f:
    lines = f.readlines()
with open('test.json', "w") as response:
    for line in lines:
        if not line.lstrip().startswith(search):
            print(line)
            response.write(line)

结果:

{

    "id": "163698b3-1e6b-4087-b398-16e2f5b1e7ef",


  },

  {

    "id": "ed433b9e-ea4e-4652-907e-03114f869774",


  },

  {

    "id": "3cd662fb-afdd-47e1-abde-364d727cfdab",


  }

推荐阅读