user12606923
user12606923

Reputation:

Deleting specific lines from .json file with Python?

Here is the problem that, I can delete the lines from my folder but I cannot choose them as their simillar way.

For example I had a .json file with 3000 lines or etc and I need to delete the lines that are starting with for example "navig". How can we modificate the Python code?

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) 

(The code is taken from another answer.)

Upvotes: 1

Views: 6054

Answers (2)

Mousam Singh
Mousam Singh

Reputation: 755

This answer would work only for JSON file and in this case, this is a robust way to the job:

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)

Upvotes: 0

Michael H.
Michael H.

Reputation: 3483

You could do something like this:

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)

or if you only want to write the file once:

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))

Upvotes: 2

Related Questions