Home > other >  Using match case with string.endswith() to handle different possible string endings
Using match case with string.endswith() to handle different possible string endings

Time:07-18

I want to iterate over a directory and sort the files based on extension into separate lists. I want to use match case to do this rather than many separate else-ifs. Something along the lines of the following:

for file in os.listdir(dirpath):
    filename = os.fsdecode(file)
    match filename.endswith():
        case endswith('.jpg')|endswith('.jpeg'): #How can I check if the 'filename' string ends with these two?
            doSomething(filename)
        case endswith('.mp4'): #Or this?
            somethingElse(filename)
        case _: #Or if it is anything else?
            doDefault(filename)

How can I check if the filename.endswith('.jpg') possibility from within the match case statement? Is there a way to "pass" the strings as cases into the function in the match statement? Am I misusing match case, would it be better to stick with else-ifs in this scenario?

CodePudding user response:

If you're specifically interested in file extensions, you could use os.path.splitext to separate out the file extension, and then run your match. Something like

for file in os.listdir(dirpath):
    filename = os.fsdecode(file)
    _, extension = os.path.splitext(filename)
    match extension:
        case '.jpg' | 'jpeg':
            doSomething(filename)
        case '.mp4':
            somethingElse(filename)
        case _:
            doDefault(filename)
  • Related