Вопрос

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