Created
May 27, 2020 01:51
-
-
Save lonsty/81c0b8bd6bc741ebf0c54756210beef7 to your computer and use it in GitHub Desktop.
List all files in dir and subdir
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from fnmatch import fnmatch | |
def list_files(dir_name: str, include: Iterable = None, exclude: Iterable = None) -> list: | |
""" | |
Get all files in a directory excluding ignored files. | |
:param dir_name: str, the root directory. | |
:param include: Iterable, the patterns to include. | |
:param exclude: Iterable, the patterns to exclude. | |
:return: list, the files with full path. | |
""" | |
if not exclude: | |
exclude = [] | |
if not include: | |
include = [] | |
list_of_file = os.listdir(dir_name) | |
all_files = [] | |
for entry in list_of_file: | |
full_path = os.path.abspath(os.path.join(dir_name, entry)) | |
for pattern in exclude: | |
if fnmatch(os.path.split(full_path)[-1], pattern): | |
break | |
else: | |
if os.path.isdir(full_path): | |
all_files += list_files(full_path, include, exclude) | |
else: | |
if not include: | |
all_files.append(full_path) | |
else: | |
for pattern in include: | |
if fnmatch(os.path.split(full_path)[-1], pattern): | |
all_files.append(full_path) | |
continue | |
return all_files |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment