문제

I want to store all the folder names except the folders which start with underscore (_) or have more than 6 characters.To get the list, i use this code

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

What change do i need to make to get the desired output.

도움이 되었습니까?

해결책

Well the simplest way is to extend the if clause of your list comprehension to contain two more clauses:

folders = [name for name in os.listdir(".") 
           if os.path.isdir(name) and name[0] != '_' and len(name) <= 6]

다른 팁

Another approach would be to use os.walk. This would traverse the entire directory tree from the top level directory you specify.

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

A list comprehension might be too unwieldy for this, so I have expanded it to make it clear what the conditions are:

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)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top