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
  • 26,085
  • 16
  • 96
  • 138
Kneerudge
  • 55
  • 10

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
  • 25,445
  • 7
  • 35
  • 44
  • 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
  • 15,644
  • 5
  • 53
  • 74
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
  • 152,028
  • 17
  • 215
  • 255