Tengo una carpeta llamada notas, naturalmente se clasificarán en carpetas, y dentro de esas carpetas también habrá subcarpetas para las subcategorías. Ahora mi problema es que tengo una función que camina a través de 3 niveles de subdirectorios:¿Cómo recorre los directorios con Python?
def obtainFiles(path):
list_of_files = {}
for element in os.listdir(path):
# if the element is an html file then..
if element[-5:] == ".html":
list_of_files[element] = path + "/" + element
else: # element is a folder therefore a category
category = os.path.join(path, element)
# go through the category dir
for element_2 in os.listdir(category):
dir_level_2 = os.path.join(path,element + "/" + element_2)
if element_2[-5:] == ".html":
print "- found file: " + element_2
# add the file to the list of files
list_of_files[element_2] = dir_level_2
elif os.path.isdir(element_2):
subcategory = dir_level_2
# go through the subcategory dir
for element_3 in os.listdir(subcategory):
subcategory_path = subcategory + "/" + element_3
if subcategory_path[-5:] == ".html":
print "- found file: " + element_3
list_of_files[element_3] = subcategory_path
else:
for element_4 in os.listdir(subcategory_path):
print "- found file:" + element_4
Tenga en cuenta que esto sigue siendo en gran medida un trabajo en progreso. Es muy feo en mis ojos ... Lo que trato de hacer aquí es revisar todas las carpetas y subcarpetas y poner todos los nombres de los archivos en un diccionario llamado "list_of_files", el nombre como "clave", y la ruta completa como "valor". La función aún no funciona del todo, pero se preguntaba cómo se usaría la función os.walk para hacer algo similar.
Gracias
posible duplicado de [Listado de directorios en Python] (http://stackoverflow.com/questions/120656/directory-listing-in-python) – kennytm
Para para responder a esta pregunta, primero debe comprender la recursión. Ver también: http://stackoverflow.com/questions/2922783/how-do-you-walk-through-the-directories-using-python –