Listing of all files in directory?
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 Pathfrom pprint import pprintdef 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_listpprint(searching_all_files('.'))
If your files have the same suffix, like .txt
, you can use rglob
to list the main directory and all subdirectories, recursively.
paths = list(Path(INPUT_PATH).rglob('*.txt'))
If you need to apply any useful Path function to each path. For example, accessing the name
property:
[k.name for k in Path(INPUT_PATH).rglob('*.txt')]
Where INPUT_PATH
is the path to your main directory, and Path
is imported from pathlib
.