I’am trying to list all directories and sub-directories and files that hangs from for example C:\Users, i have managed to list all directories or all files, but i can do both at the same time.
Here i list the subdirectories from C:/Users/XXX/Desktop:
import os
ejemplo_dir = 'C:/Users/XXX/Desktop'
with os.scandir(ejemplo_dir) as ficheros:
subdirectorios = [fichero.name for fichero in ficheros if fichero.is_dir()]
print(subdirectorios)
Here i list the files from C:/Users/XXX/Desktop:
import os
ejemplo_dir2 = 'C:/Users/XXX/Desktop'
with os.scandir(ejemplo_dir2) as ficheros:
ficheros = [fichero.name for fichero in ficheros if fichero.is_file()]
print(ficheros)
Someone has some idea of how I can list everything at once?
THX=)
>Solution :
Try using a loop with os.walk and PurePath
import os
from pathlib import PurePath
ROOT = "C:\Users"
for path, subdirs, files in os.walk(ROOT):
for name in files:
pure_path = PurePath(path, name)
print(pure_path)
See: Python list directory, subdirectory, and files