Listing of all files in directory?

Can anybody help me create a function which will create a list of all files under a certain directory by using pathlib library?

Here, I have a:

enter image description here

I have

  • c:\desktop\test\A\A.txt

  • c:\desktop\test\B\B_1\B.txt

  • c:\desktop\test\123.txt

I expected to have a single list which would have the paths above, but my code returns a nested list.

Here is my code:

from pathlib import Path

def searching_all_files(directory: Path):   
    file_list = [] # A list for storing files existing in directories

    for x in directory.iterdir():
        if x.is_file():

           file_list.append(x)
        else:

           file_list.append(searching_all_files(directory/x))

    return file_list


p = Path('C:\\Users\\akrio\\Desktop\\Test')

print(searching_all_files(p))

Hope anybody could correct me.


Use Path.glob() to list all files and directories. And then filter it in a List Comprehensions.

p = Path(r'C:\Users\akrio\Desktop\Test').glob('**/*')
files = [x for x in p if x.is_file()]

More from the pathlib module:

  • pathlib, part of the standard library.
  • Python 3's pathlib Module: Taming the File System

from pathlib import Path
from pprint import pprint

def searching_all_files(directory):
    dirpath = Path(directory)
    assert dirpath.is_dir()
    file_list = []
    for x in dirpath.iterdir():
        if x.is_file():
            file_list.append(x)
        elif x.is_dir():
            file_list.extend(searching_all_files(x))
    return file_list

pprint(searching_all_files('.'))