pythonregexstringos.walk

Using endswith with case insensitivity in python


I have a list of file extensions and I have to write if conditions. Something like

ext = (".dae", ".xml", ".blend", ".bvh", ".3ds", ".ase",
           ".obj", ".ply", ".dxf", ".ifc", ".nff", ".smd",
           ".vta", ".mdl", ".md2", ".md3",
           ".pk3", ".mdc", ".x",
           ".q3o", ".q3s", ".raw",
           ".ac", ".dxf", ".irrmesh",
           ".irr", ".off", ".ter",
           ".mdl", ".hmp", ".mesh.xml",
           ".skeleton.xml", ".material", ".ms3dv",
           ".lwo", ".lws", ".lxo",
           ".csm", ".cob", ".scn",
           ".xgl", ".zgl")
for folder, subfolders, filename in os.walk(directory):
    if any([filename.endswith(tuple(ext)) for filename in filenames]):

I realized that endswith is case sensitive. How I could treat, for instance, ".xml" and ".XML" as the same extensions?


Solution

  • Simply call lower to make the string lowercase before calling endswith:

    ext = (".dae", ".xml", ".blend", ".bvh", ".3ds", ".ase",
               ".obj", ".ply", ".dxf", ".ifc", ".nff", ".smd",
               ".vta", ".mdl", ".md2", ".md3"
               ".pk3", ".mdc", ".x"
               ".q3o", ".q3s", ".raw"
               ".ac", ".dxf", ".irrmesh"
               ".irr", ".off", ".ter"
               ".mdl", ".hmp", ".mesh.xml"
               ".skeleton.xml", ".material", ".ms3dv"
               ".lwo", ".lws", ".lxo"
               ".csm", ".cob", ".scn"
               ".xgl", ".zgl")
    for folder, subfolders, filename in os.walk(directory):
        if any([filename.lower().endswith(tuple(ext)) for filename in filenames]):