reading content of a directory and its subdirectories with python

Solution 1:

What i understood is you just wanted to list all the filenames from a particular directory and its sub-directory.

list1=[] #Empty list

for root, dirs, files in os.walk(fr"path\\to\\directory", topdown=False): 
#Listing Directory
    for name in files:
        a=os.path.join(root, name)
        print(a)
        list1.append(a)

Solution 2:

import os
path="C://Users//<user_name>//Desktop"
obj = os.scandir()
print("Files and Directories in '% s':" % path)
for entry in obj:
    if entry.is_dir() or entry.is_file():
        print(entry.name)

For listing whole directory:

import os
def list_dirs(path):
  obj = os.scandir(path)
  for entry in obj:
      if entry.is_dir():
        print(1,entry.path)
        list_dirs(entry)
      elif entry.is_file():
        print(2,entry.name)
      else:
        break
list_dirs(path)

It basically use's os.scandir method which provides both speed and more benefit like file meta data ect, with recursion to obtain list of whole directory.

also a list comprehension method for @FaraazKurawle 's answer:

def list_dir(path):
  path=fr"{path}"
  list_1=[os.path.join(root, name) for root, dirs, files in os.walk(path, topdown=False) for name in files]
  return list_1

some helpful links:

  • List all directory
  • Os.scandir
  • os.scandir vs os.listdir vs os.walk

Solution 3:

import glob
path = '\\path\\to\\dir\\'
files = [f for f in glob.glob(path + "**/*", recursive=True)]