3

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.

smci
  • 32,567
  • 20
  • 113
  • 146
Kneerudge
  • 55
  • 11
  • Do you need the recursive `os.walk` or not? – smci Apr 15 '14 at 08:49
  • i used @dr-jimbob solution 'folders = [name for name in os.listdir(".") if os.path.isdir(name) and name[0] != '_' and len(name) <= 6]' – Kneerudge Apr 15 '14 at 08:54
  • Do you mean you don't need recursive then? You should edit the question to say, because your question is ambiguous. – smci Apr 15 '14 at 08:56

3 Answers3

1

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
sateesh
  • 27,947
  • 7
  • 36
  • 45
  • i did not try with os.walk. I'll give this a try – Kneerudge Apr 15 '14 at 08:53
  • Bug: exclude-condition `not d.startswith('_') and len(d)>6` should be '<=6'. `not` is taking precedence over `and`. Use parens for clarity: – smci Apr 15 '14 at 09:04
  • @smci why so ? OP wants * folders that doesn't start with _ and * folders that have length >6 . Boolean NOT has a higher precedence over boolean AND, so the above conditional would be fine. Though adding parentheses to disambiguate would have been better. – sateesh Apr 15 '14 at 10:32
1

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]
dr jimbob
  • 17,259
  • 7
  • 59
  • 81
0

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)
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284