EdgarA
EdgarA

Reputation: 23

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

Upvotes: 0

Views: 39

Answers (1)

Nishant
Nishant

Reputation: 21924

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)

Upvotes: 1

Related Questions