Selecting folders using strings in Python
Simple question here: I'm trying to identify folders with a specific string in their name, but I want to specify some additional exclusion criteria. Right now, I'm looking for all folders that begin with a specific string using this syntax:
import开发者_如何转开发 os
parent_cause = 'B03'
path = ('filepath')
child_causes = [x for x in os.listdir(path) if x.startswith(parent_cause + '.')]
While this does identify the subfolders I am looking for ('B03.1', 'B03.2'), it also includes deeper subfolders which I want to exclude ('B03.1.1', 'B03.1.2'). Any thoughts on a simple algorithm to identify subfolders which begin the the string, but exclude ones which contain two or more '.' than the parent?
NOt sure I fully understand the issues, but I suggest os.walk
good_dirs = []
bad_dirs = []
for root, files, dirs in os.walk("/tmp/folder/B03"):
# this will walk recursively depth first into B03
# root will be the pwd, so we can test for that
if root.count(".") == 1: ###i think aregex here might help
good_dirs.append(root)
else:
bad_dirs.append(root)
try using regex
import os
import re
parent_cause = 'B03'
path = ('filepath')
validPath = []
for eachDir in os.listdir(path):
if re.match('^%s\.\d+$' % parent_cause, eachDir):
validPath.append(path+'/'+eachDir)
精彩评论