简体   繁体   中英

How to delete particular content from a file using python

I have the following JSON file which contains some content(1st line and last line) due to which I am unable to load it as a JSON file. I want to edit this file using python so that I only have the content inside {} braces and "source.value(" & ");"are removed.

source.value(
{Meli:1,jack:3,rustin:4}
);


    with open('check.json', 'rb') as g:
        b=json.load(g)
    
    
    Traceback (most recent call last):
      File "<input>", line 2, in <module>
        raise JSONDecodeError("Expecting value", s, err.value) from None
    json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I'm not sure how best to generalize for your specific problem since many things could change based on how these files are generated.

First off the json format requires the names to be in double quotes - {"Meli":1,"jack":3,"rustin":4}

Assuming this is fixed, we open the file, read the lines and only use json to read the second line. Remember python indexes from 0.

import json

with open('test.json', 'r') as file:
    lines = file.readlines()
    data = json.loads(lines[1])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM