python change the value of a specific line

Category: python (3 Views)

I have a 1000 json files, I need to change the value of a specific line with numeric sequence in all files.

An example

the specific line is - "name": "carl 00",

I need it to be like following

File 1

"name": "carl 1",

File 1

"name": "carl 2",

File 3

"name": "carl 3",

What is the right script to achieve the above using python

🔴 No definitive solution yet

📌 Solution 1

Without knowing more, the below loop will accomplish the posts requirements.

name = 'carl'
for i in range(0,1001):
    print(f'name: {name} {i}')

📌 Solution 2

This should do the trick. But you're not very clear about how the data is stored in the actual json file. I listed two different approaches. The first is to parse the json file into a python dict then manipulate the data and then turn it back into a character string and then save it. The second is what I think you mean by "line". You can split the file's character string into a list then change the line you want, and remake the full string again, then save it.

This also assumes your json files are in the same folder as the python script.

import os
import json

my_files = [name1, name2, name3, ...]      # ['file_name.json', ...]

folder_path = os.path.dirname(__file__)

for i, name in enumerate(my_files):
   path = f'{folder_path}/{name}'
   with open(path, 'r') as f:
      json_text = f.read()
      
   # if you know the key(s) in the json file...
   json_dict = json.loads(json_text)   
   json_dict['name'] = json_dict['name'].replace('00', str(i))
   new_json_str = json.dumps(json_dict)

   # if you know the line number in the file...
   line_list = json_text.split('\n')
   line_list[line_number - 1] = line_list[line_number - 1].replace('00', str(i))
   new_json_str = '\n'.join(line_list)

   with open(path, 'w') as f:
      f.write(new_json_str)

Based on your edit, this is what you want:

import os
import json

my_files = [f'{i}.json' for i in range(1, 1001)]

folder_path = os.path.dirname(__file__)   # put this .py file in same folder as json files

for i, name in enumerate(my_files):
   path = f'{folder_path}/{name}'
   with open(path, 'r') as f:
      json_text = f.read()
      
   json_dict = json.loads(json_text)   
   json_dict['name'] = f'carl {i}'
   

   # include these lines if you want "symbol" and "subtitle" changed
   json_dict['symbol'] = f'carl {i}'
   json_dict['subtitle'] = f'carl {i}'


   new_json_str = json.dumps(json_dict)

   with open(path, 'w') as f:
      f.write(new_json_str)