Search code examples
pythoncontainsmetacharacters

Python: filename contains String (metachar?)


I'm using os.walk(directory) to show recursively all the files from that directory. The thing is that i need to show only the files that contain an asked String in its name, and it has to manage metachars too.

What i have now is:

for root, subdirs, files in os.walk(dir1):
        for filename in files:
            if substring in filename:
                name_path = os.path.join(root,filename)
                list.insert(END, name_path)

This works nicely, but if substring = *, as i dont have files containing an ' * ', my list is empty.

So, how do I get this to work if substring contains a METACHAR?


Solution

  • I think you are looking for fnmatch:

    https://docs.python.org/3/library/fnmatch.html#module-fnmatch