我有一个小脚本遍历工作区,并将类型.asc的相同文件名添加到字典中的列表中。但是,我想省略工作区内某些文件夹中的所有.asc文件(以蓝色突出显示)。如何在蓝色突出显示的文件夹中省略.asc文件,或者只包含位于子块文件夹中的.asc文件?
import os, collections
from collections import defaultdict
workspace = r'C:\my\workspace'
# Get a list of all files in subfolders
rasters = defaultdict(list)
for root, dirs, files in os.walk(workspace):
for file in files:
if file.endswith(".asc"):
rasters[file].append(os.path.join(root, file))
rasters = rasters.values()
答案 0 :(得分:2)
for current_dir, dirs, files in os.walk(workspace):
if current_dir.endswith("IgnoreMe"):
continue #skip this folder
for file in files:
if file.endswith(".asc"):
rasters[file].append(os.path.join(root, file))
更具体地适合你
for current_dir, dirs, files in os.walk(workspace):
if "_" not in os.path.split(current_dir)[-1]:
#filter out all ".asc" files
files = filter(lambda fname:not fname.endswith("asc"),files)
for file in files:
#these dont have any more ".asc" files