Home > Software engineering >  Modify multiple json files
Modify multiple json files

Time:09-15

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

CodePudding user response:

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

CodePudding user response:

You can add your code to a loop that changes the name of the file for every turn like

import json

file_no = int(input('Enter number of files to edit: '))
y = None

for x in range(1, file_no   1):
    file_name = str(x)   '.json'
    with open(file_name, 'r') as f:
        data = json.load(f)
        for j in data:
            if j.lower() == 'name':
                data[j] = f"Testname #{x}"
                y = data
                break
    
    with open(file_name, 'w') as g:
        json.dump(y, g, indent=4)

This will go for as many files as the number entered.

CodePudding user response:

I Think you'll have to open one file after the other. I don't see any other way.

for file_name in list_of_filenames:
    with open(file_name) as file:
        # read file
  • Related