Home > Back-end >  Parse string that defines a user-specified format for a file name in Python?
Parse string that defines a user-specified format for a file name in Python?

Time:09-08

I'm trying to allow users to define a string such as '%X/%P_%D_%d.txt' where each format code %X corresponds to a given variable in Python. This format is then used to specify the file name and path. Parsing is similar to datetime's strptime(), but they have a pretty rigid base structure it seems and do it via regex. I was thinking of linking the format code and the variable with a dictionary, i.e.

fdict = {r'%X' : 'X001', r'%P' : 'Part5', r'%D' : 1, r'%d' : 2}

(the values are just placeholders for variables). But honestly can't find any examples of anything similar and it seems like regex might not be the right way to approach this. Are there any modules that would work? Or better keywords?

CodePudding user response:

An f-string might work well here:

fdict = {r'%X' : 'X001', r'%P' : 'Part5', r'%D' : 1, r'%d' : 2}
filename =  f"{fdict['%X']}/{fdict['%P']}_{fdict['%D']}_{fdict['%d']}.txt"
print(filename)  # X001/Part5_1_2.txt

You could also use re.sub with a callback function:

fdict = {r'%X' : 'X001', r'%P' : 'Part5', r'%D' : '1', r'%d' : '2'}
filename = "%X/%P_%D_%d.txt"
regex = r'|'.join(fdict.keys())
output = re.sub(regex, lambda m: fdict[m.group()], filename)
print(output)  # X001/Part5_1_2.txt
  • Related