3

我想存储除以下划线 (_) 开头或超过 6 个字符的文件夹之外的所有文件夹名称。要获取列表,我使用此代码

folders = [name for name in os.listdir(".") if os.path.isdir(name)]

我需要进行哪些更改才能获得所需的输出。

4

3 回答 3

1

另一种方法是使用os.walk。这将从您指定的顶级目录遍历整个目录树。

import os
from os.path import join
all_dirs  = []

for root,dirs,filenames in os.walk('/dir/path'):
    x = [join(root,d) for d in dirs if not d.startswith('_') and len(d)>6]
    all_dirs.extend(x)
print all_dirs # list of all directories matching the criteria
于 2014-04-15T07:28:06.583 回答
1

那么最简单的方法是扩展列表推导的 if 子句以包含另外两个子句:

folders = [name for name in os.listdir(".") 
           if os.path.isdir(name) and name[0] != '_' and len(name) <= 6]
于 2014-04-15T07:35:14.190 回答
0

列表理解可能对此过于笨拙,因此我对其进行了扩展以明确条件是什么:

folders = []

for name in os.listdir('.'):
   if os.path.isdir(name):
      dirname = os.path.basename(name)
      if not (dirname.startswith('_') or len(dirname) > 6):
         folders.append(name)
于 2014-04-15T07:07:00.157 回答