简体   繁体   中英

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM