我想编写一个代码,在给定主文件夹的子文件夹中查找文件,该主文件夹具有特定的扩展名并且在其子文件夹的名称中包含一些单词。我怎样才能做到这一点?
例如,获取其文件夹名称中包含单词“dis”的文件,并获取其中具有 shp 扩展名的文件。
这是我尝试过的:
只有名字的部分没有被覆盖。
rootfolder= directory
shapelist = []
for path, subdirs, files in os.walk(rootfolder):
for name in files:
if name.endswith('.shp'):
shapelist.append(os.path.join(path, name))
这棵树是这样的:
rootfolder\
subfolders(including two that have the words diss)\
files inside these
希望它是清楚的。
请您参考如下方法:
使用你的方法和os.path.split
shapelist = []
for path, subdirs, files in os.walk(rootfolder):
# check if 'dis' is in the name of the subfolder
if 'dis' in os.path.split(path)[-1]:
for name in files:
if name.endswith('.shp'):
shapelist.append(os.path.join(path, name))
但这是使用 glob 的更好方法
from glob import glob
shapelist = glob(rootfolder + '/**/*dis*/*.shp', recursive=True)
