I have a folder with 2000 json files and I have to edit specific line with number based on file name.
files names :-
1.json 2.json 3.json ... 1999.json 2000.json
each file contain text like below:-
1.json
{ "Name": "Testname #5", "Description": }
2.json
{ "Name": "Testname #5", "Description": }
Currently no is not in correct order. I want to make like this :
1.json
{ "Name": "Testname #1", "Description": }
2.json
{ "Name": "Testname #2", "Description": }
100.json
{ "Name": "Testname #100", "Description": }
I have done something like this
import os import sys import fileinput x = 0; for line in fileinput.input(['1.json'], inplace=True): if line.strip().startswith('"name"'): line = '"name":"Testname #' + str(x) + '",n' x += 1 sys.stdout.write(line)
this is works for 1 file at a time. I need to do bulk edit. can anyone help me
Advertisement
Answer
If they are valid JSON files use the json
parser:
import json for i in range(1, 2001): with open(f'{i}.json', 'r+', encoding='utf8') as f: data = json.load(f) data['Name'] = f'Testname #{i}' f.seek(0) # rewind f.truncate() # delete old content json.dump(data, f, indent=4) # write new content