Search code examples
pythonfilenamesglobfnmatch

Working with multiple filename patterns in python


I'm struggling to get a couple of things together as, since I've got a code together that works with a particular file pattern (i.e FILENAME_IDENTIFIER_NUMBER.filetype) I have some old files that do not match this particular filename structure that are throwing up errors when I'm trying to work with the mixed names.

is there a way that I can search for files that do not match this file structure? I have tried using glob and cannot get it to match. fnmatch when used with _. will give me both options as the wildcard presumably accepts anything after the first underscore anyway.

for example I will have, in multiple directories, filenames such as:

filename_identifier_number.extension filename_number.extension

where I would normally split the above with:

for f in files:
filepath = os.path.join(subdir,f)
        fname,fext = os.path.split(f)
        filename,identifier,number = fname.split("_")

this will work but obviously I will get the error when there is only one underscore in the filename.

Can I either ignore this error? (I have tried the below):

try:
print(filename)
except ValueError:
pass

However this doesn't work.

or is there a way I can search for any filename which doesn't match the format I require (filename_identifier_number) and develop something that handles them in another way?

Thanks,


Solution

  • Maybe this?

    fname, fext = os.path.split(f)
    parts = fname.split("_")
    if len(parts) != 3:
        ...     # Handle invalid file name
    else:
        filename, identifier, number = parts