我想列出所有 txt
目录结构中的文件,但排除某些特定文件夹。
例如我想获取所有 txt
D:\_Server\<subfolders>\Temp_1\Config\
或
D:\_Server\<subfolders>\Temp_1\Config\Stat
但排除
D:\_Server\<subfolders>\Temp_1\Config\Historie\
和
D:\_Server\<subfolders>\Temp_1\Config\Archive\
为了获取所有文件,我使用了以下代码:
glob.glob('D:\\_Server\\**\\Config\\**\\*.olc', recursive=True)
这会产生所有 txt
的列表文件还有 Archive
中的文件和Historie
文件夹。
这对于 Python 来说可能吗 Glob
模块?或者有更好的解决方案来存档吗?
最佳答案
您也可以使用os
来做到这一点:
import os
extensions = ('.txt') #extinctions want to search
exclude_directories = set(['exclude_directory_name']) #directory (only names) want to exclude
for dname, dirs, files in os.walk('/root/path/to/directory'): #this loop though directies recursively
dirs[:] = [d for d in dirs if d not in exclude_directories] # exclude directory if in exclude list
for fname in files:
if(fname.lower().endswith(extensions)): #check for extension
fpath = os.path.join(dname, fname) #this generate full directory path for file
print fpath
关于Python列出子目录中的所有文件但排除某些目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55394131/