【问题标题】:Selecting folders using strings in Python在 Python 中使用字符串选择文件夹
【发布时间】:2011-09-11 18:32:03
【问题描述】:

这里有一个简单的问题:我正在尝试识别名称中包含特定字符串的文件夹,但我想指定一些额外的排除标准。现在,我正在使用以下语法查找以特定字符串开头的所有文件夹:

import os
parent_cause = 'B03'
path = ('filepath')
child_causes = [x for x in os.listdir(path) if x.startswith(parent_cause + '.')]

虽然这确实确定了我正在寻找的子文件夹('B03.1'、'B03.2'),但它还包括我想要排除的更深层次的子文件夹('B03.1.1'、'B03.1.2') .关于识别以字符串开头的子文件夹的简单算法的任何想法,但排除包含两个或多个“。”的子文件夹。比父母?

【问题讨论】:

  • 不确定它的性能如何,但您可以尝试将这个和条件添加到您的列表中 - ... if x.startswith(parent_cause + '.') and x.count('.') == 1]

标签: python string directory


【解决方案1】:

不确定我是否完全理解这些问题,但我建议使用 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)

【讨论】:

    【解决方案2】:

    尝试使用正则表达式

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-07
      • 1970-01-01
      • 2017-10-29
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      相关资源
      最近更新 更多