Explorar archivos y subcarpetas en Python


Me gustaría navegar a través de la carpeta actual y todas sus subcarpetas y obtener todos los archivos con .htm|.extensiones html. He descubierto que es posible averiguar si un objeto es un dir o un archivo como este:

import os

dirList = os.listdir("./") # current directory
for dir in dirList:
  if os.path.isdir(dir) == True:
    # I don't know how to get into this dir and do the same thing here
  else:
    # I got file and i can regexp if it is .htm|html

Y al final, me gustaría tener todos los archivos y sus rutas en una matriz. ¿Es algo así posible?

Author: alain.janinm, 2011-04-28

5 answers

Puede utilizar os.walk() para iterar recursivamente a través de un directorio y todos sus subdirectorios:

for root, dirs, files in os.walk(path):
    for name in files:
        if name.endswith((".html", ".htm")):
            # whatever

Para construir una lista de estos nombres, puede usar una comprensión de lista:

htmlfiles = [os.path.join(root, name)
             for root, dirs, files in os.walk(path)
             for name in files
             if name.endswith((".html", ".htm"))]
 93
Author: Sven Marnach,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-01 17:06:26

Use newDirName = os.path.abspath(dir) para crear un nombre de ruta de directorio completo para el subdirectorio y luego enumere su contenido como lo ha hecho con el padre (es decir, newDirList = os.listDir(newDirName))

Puede crear un método separado de su fragmento de código y llamarlo recursivamente a través de la estructura del subdirectorio. El primer parámetro es el directorio pathname. Esto cambiará para cada subdirectorio.

Esta respuesta se basa en la documentación de la versión 3.1.1 de la Biblioteca Python. Hay un buen ejemplo modelo de esto en acción en la página 228 de la Referencia de la Biblioteca Python 3.1.1 (Capítulo 10-Acceso a Archivos y Directorios). ¡Buena suerte!

 3
Author: NeonJack,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-17 00:08:24

Tenía algo similar en lo que trabajar, y así es como lo hice.

import os

rootdir = os.getcwd()

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        #print os.path.join(subdir, file)
        filepath = subdir + os.sep + file

        if filepath.endswith(".html"):
            print (filepath)

Espero que esto ayude.

 2
Author: Pragyaditya Das,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-11 05:23:50

Versión ligeramente alterada de la solución de Sven Marnach..


import os

Folder_location = 'C:\SomeFolderName' file_list = create_file_list(folder_location)

Def create_file_list(path): return_list = []

for filenames in os.walk(path): for file_list in filenames: for file_name in file_list: if file_name.endswith((".txt")): return_list.append(file_name) return return_list

 0
Author: campervancoder,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-05 21:14:46

En python 3 puedes usar el sistema operativo.scandir ():

for i in os.scandir(path):
    if i.is_file():
        print('File: ' + i.path)
    elif i.is_dir():
        print('Folder: ' i.path)
 0
Author: Spas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-12 15:12:30