1

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

3
  • 1
    You really should load your json with json.load(), filter and then json.dump() it. Don't filter by substring or regex - you will end with a clbuttic mistake. Commented Dec 27, 2019 at 10:53
  • The initial code which you presented would work for normal text file, just replace line.strip() with line.startswith('sometext'). But if you want to handle a json file specifically than you will have to load the json first and then delete the keys in the similar fashion. Commented Dec 27, 2019 at 10:55
  • I solved it with that way. Thanks for all help. ^^ Commented Dec 27, 2019 at 11:06

2 Answers 2

2

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))
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.