Home > OS >  Rename and read multiple JSON files in python
Rename and read multiple JSON files in python

Time:02-21

I'm trying to rename my 6 JSON files present in logs folder using python. Say I have files like-

File1: results_HAT_6e0_57-graph_52.19_test_results_tests_storage.Full.up_ bargraph _results-chart

File2: results_HAT_6e0_55-graph_52.19_test_results_tests_storage.Full.down_ bargraph _results-chart

File3: results_HAT_6e0_58-graph_52.2_test_results_tests_storage.Full.up_ bargraph _results-chart

File4: results_HAT_6e0_56-graph_52.2_test_results_tests_storage.Full.down_ bargraph _results-chart

File5: results_HAT_6e0_59-graph_52.242_test_results_tests_storage.Full.up_ bargraph _results-chart

File6: results_HAT_6e0_54-graph_52.242_test_results_tests_storage.Full.down_bargraph_results-chart

and i want to make it more easy to understand , therefore want to rename it like:

File1: 52.19_up

File2: 52.19_down

File3: 52.2_up

File4: 52.2_down

File5: 52.242_up

File6: 52.242_down

PS- the values after dot(.) may vary. eg- 52.67, 52.9, 52.002...

I tried doing through this similar method-

import numpy as np
import os

os.chdir(r'C:\Users\me\desktop\json\logs')
print(os.getcwd())

for count, f in enumerate(os.listdir()):
    f_name, f_ext = os.path.splitext(f)
    f_name = "f"   str(count)

    new_name = f'{f_name}{f_ext}'
    os.rename(f, new_name)

with open('f0.json', 'r') as f1:              
    data1 = json.load(f1)

with open('f1.json', 'r') as f2:                      
    data2 = json.load(f2)

with open('f2.json', 'r') as f3:                    
    data3 = json.load(f3)

with open('f3.json', 'r') as f4:                   
    data4 = json.load(f4)

with open('f4.json', 'r') as f5:                       
    data5 = json.load(f5)

with open('f5.json', 'r') as f6:                     
    data6 = json.load(f6)

But through this method, files are renaming as f0...f5. which is still confusing and unclear. Any help would be appreciated.

CodePudding user response:

Well, Im not sure about the format of these filenames. But as the file names you provided. I can suggest this:

import re
import glob
import os 

files = glob.glob("/home/adam/*")
for file in files:
    prefix = re.findall(r"_(\d \.\d )_", file)
    postfix = re.findall(r"Full\.(\w )_", name)
    prefix = prefix[0] if prefix else ""
    postfix = postfix[0] if postfix else ""
    new_name = f"{prefix}_{postfix}"
    os.rename(file, new_name)

CodePudding user response:

You could do it this way:

for count, f in enumerate(os.listdir()):
    f_name, f_ext = os.path.splitext(f)
    f_name = "f"   str(count)
    f_name_split = f.split('_')
    new_name = f"{f_name_split[4]}_{f_name_split[8].split('.')[-1]}{f_ext}"
    os.rename(f, new_name)

Note: If the file name structure changes, then it will probably not work anymore.

  • Related