Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Parse string that defines a user-specified format for a file name in Python?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading