I need to list all files with the containing directory path inside a folder. I tried to use os.walk
, which obviously would be the perfect solution.
However, it also lists hidden folders and files. I'd like my application not to list any hidden folders or files. Is there any flag you can use to make it not yield any hidden files?
Cross-platform is not really important to me, it's ok if it only works for linux (.* pattern)
No, there is no option to
os.walk()
that'll skip those. You'll need to do so yourself (which is easy enough):Note the
dirs[:] =
slice assignment; we are replacing the elements indirs
(and not the list referred to bydirs
) so thatos.walk()
will not process deleted directories.This only works if you keep the
topdown
keyword argument toTrue
, from the documentation ofos.walk()
:I realize it wasn't asked in the question, but I had a similar problem where I wanted to exclude both hidden files and files beginning with
__
, specifically__pycache__
directories. I landed on this question because I was trying to figure out why my list comprehension was not doing what I expected. I was not modifying the list in place withdirnames[:]
.I created a list of prefixes I wanted to exclude and modified the dirnames in place like so: