我需要列出文件夹内包含目录路径的所有文件。我尝试使用 os.walk
,这显然是完美的解决方案。
但是,它也列出了隐藏的文件夹和文件。我希望我的应用程序不列出任何隐藏的文件夹或文件。有没有什么标志可以用来让它不产生任何隐藏文件?
跨平台对我来说并不是很重要,如果它只适用于linux(.*模式)就可以了
最佳答案
不,os.walk()
没有选项可以跳过这些。您需要自己这样做(这很容易):
for root, dirs, files in os.walk(path):
files = [f for f in files if not f[0] == '.']
dirs[:] = [d for d in dirs if not d[0] == '.']
# use files and dirs
注意 dirs[:] =
切片赋值; os.walk
递归遍历 dirs
中列出的子目录。通过将 dirs
的 元素 替换为满足条件的元素(例如,名称不以 .
开头的目录), os.walk()
不会访问不符合条件的目录。
这仅在您将 topdown
关键字参数保留为 True
时才有效,来自 documentation of os.walk()
:
When
topdown
isTrue
, the caller can modify the dirnames list in-place (perhaps usingdel
or slice assignment), andwalk()
will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, impose a specific order of visiting, or even to informwalk()
about directories the caller creates or renames before it resumeswalk()
again.
关于python - os.walk 没有隐藏文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13454164/