在Python中排除以underscore开头或字符超过六个的文件夹
我想把所有文件夹的名字都存起来,但不包括那些以下划线 (_) 开头的文件夹和名字超过6个字符的文件夹。为了得到这个列表,我用这段代码:
folders = [name for name in os.listdir(".") if os.path.isdir(name)]
我需要做什么改动才能得到我想要的结果呢?
3 个回答
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)
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
1
最简单的方法就是在你的列表推导式的if条件中添加两个额外的条件:
folders = [name for name in os.listdir(".")
if os.path.isdir(name) and name[0] != '_' and len(name) <= 6]