Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to list directory and its subdirectories and its files? In python

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading