pythonlist-comprehensiondirectory-walk

In python exclude folders which start with underscore or more than six characters long


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.


Solution

  • 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]