Listing of all files in directory?

Akrios picture Akrios · Oct 7, 2016 · Viewed 77.8k times · Source

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.

Answer

prasastoadi picture prasastoadi · Oct 24, 2016

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: