Better way / regex to extract values form a dictionary

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Jul 21 08:21:05 EDT 2018


On Sat, 21 Jul 2018 17:07:04 +0530, Ganesh Pal wrote:

> I have one of the dictionary values in the below format
> 
> '/usr/local/ABCD/EDF/ASASAS/GTH/HELLO/MELLO/test04_Failures.log'
> '/usr/local/ABCD/EDF/GTH/HEL/OOLO/MELLO/test02_Failures.log'
> '/usr/local/ABCD/EDF/GTH/BEL/LO/MELLO/test03_Failures.log'
> 
> I need to extract the file name in the path example, say
> test04_Failure.log and testcase no i.e test04

The dictionary is irrelevant to your question. It doesn't matter whether 
the path came from a dict, a list, read directly from stdin, an 
environment variable, extracted from a CSV file, or plucked directly from 
outer space by the programmer. The process remains the same regardless of 
where the path came from.


import os
path = '/usr/local/ABCD/EDF/ASASAS/GTH/HELLO/MELLO/test04_Failures.log'

filename = os.path.basename(path)
print filename
# prints 'test04_Failures.log'

testcase, remaining_junk = filename.split('_', 1)
print testcase
# prints 'test04'



-- 
Steven D'Aprano
"Ever since I learned about confirmation bias, I've been seeing
it everywhere." -- Jon Ronson



More information about the Python-list mailing list