Domanda

I have a little script that walks through a workspace and adds identical file names of type .asc to a list in a dictionary. However, I would like to omit all .asc files in certain folders within the workspace (highlighted in blue). How can I omit .asc files in the folders highlighted in blue, or alternatively, only include .asc files located in the subblock folders?

enter image description here

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()
È stato utile?

Soluzione

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))

more specifically for you

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top