I need to index some folders from a defined directory into a list. The code below works fine, but the problem is that it also indexes all the other types of files (jpeg, png…).
Is there a way to make an ‘if’ statement to check the type of the file, so it only indexes folder types? Since the folders don’t have extensions… I’m on Windows…
def folders_in_a_list(self, context):
dirListing = os.listdir("C:\some_path")
list_of_folders = []
for item in dirListing:
# Pseudo Code
if item == folder_type # How can I make sure the items are exclusively folders and not any other type of files?
list_of_folders.append(item)
your first example would work if you passed isdir the full path. “item” is a string, so you’re just getting the individual folder name, not some object that os.path can use to get more information. in other words:
import os
from pprint import pprint as pp
list_of_folders = []
search_path = "C:/windows/"
for item in os.listdir(search_path):
if os.path.isdir(search_path + item):
list_of_folders.append(item)
pp(list_of_folders)
edit: worth noting that os.walk is the same way, it just returns strings and you’ll need to do more work to turn them into file references or whatever you need.
One last question, I have a drop down list that indexes all the folders from a main folder. I want the button with a ‘folder’ icon to open that selected folder in Windows explorer.
How do I retrieve the name (as a string) of the selected folder via that drop down list?
I want use the string name to concatenate it to the main folder’s path…
I put here only the relevant code:
class OpenCategoryFolder(bpy.types.Operator):
bl_idname = "open.category_folder"
bl_label = "Open Category Folder"
bl_description = "Open selected category's folder in Windows explorer"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
lib_path = context.preferences.addons[__name__].preferences.sculpt_alphas_library
selected_category_name = # What should I put here if I want to have the name of the selected folder as a string?
os.startfile(lib_path + os.sep + selected_category_name)
return {'FINISHED'}
class CategoryPropertyScene(bpy.types.PropertyGroup):
Categories: EnumProperty(items = preview_sub_folders_categories)
def sculpt_alphas_categories_prepend(self, context):
layout = self.layout
row = layout.row(align=True)
row.prop(context.scene.category_pointer_prop, "Categories", text = '')
row.operator("open.category_folder", text = "", icon ="FILE_FOLDER")
def register():
Scene.category_pointer_prop = bpy.props.PointerProperty(type = CategoryPropertyScene)