Python: filename contains String (metachar?)
Asked Answered
T

2

13

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?

Triglyph answered 29/3, 2016 at 20:43 Comment(0)
E
18

I think you are looking for fnmatch:

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

Ennead answered 29/3, 2016 at 20:46 Comment(2)
LOL. now I get this working ONLY if I introduce a metachar. If substring is something like "exercise1" it doesnt find itTriglyph
Found it. substring must be substring=" * "+substring+" * "Triglyph
P
4

You can use glob. It's very handy and similar to find command in Linux.

import glob
glob.glob("/home/user/*.txt")

Search in multiple subdirectories

glob.glob("/home/user/*/*.txt")

or

glob.glob("/home/user/logs?.txt")
Pandich answered 11/5, 2019 at 18:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.