EdgarA EdgarA - 14 days ago 5
JSON Question

Python file handling based on string

I have large dump of .json files that are sorted by their ID like this: for example TRAMGJJ128F421487E.json is sorted in files based on 3rd - 5th letters so this would be in directory: ../A/M/G/TRAMGJJ128F421487E.json

My question is: how do I open the right file based on given ID?
There are A-Z/A-Z/A-Z/ files in every directory

Answer

Can't you just work it out by splitting strings?

base = "/" #  Your base directory here
json_file = 'TRAMGJJ128F421487E.json'  # Input ID
folder_one, folder_two, folder_three = json_file[2:5]
filename = os.path.join(base,
                        folder_one,
                        folder_two,
                        folder_three,
                        json_file)

And in Python 3.5 you can just unpack an iterable on the fly:

base = "/" #  Your base directory here
json_file = 'TRAMGJJ128F421487E.json'  # Input ID
os.path.join(base, *json_file[2:5], json_file)