Last active
February 6, 2023 07:32
-
-
Save nodewee/eae12e2b74beb82162b8b488648f1fdd to your computer and use it in GitHub Desktop.
This file contains 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
def list_files( | |
dir: str, | |
ext: list or str = None, | |
recursive: bool = True, | |
excludes: list = None, | |
): | |
""" | |
Args: | |
- dir, directory path. | |
- ext, file extension list, lowercase letters, such as ".txt". Default is None, which means all files. | |
- recursive, Default is True, will list files in subfolders. | |
- excludes, exclude folder or file name list, regexp pattern string. Default is None, which means all folders | |
Tips: | |
- How to get relative path of a file: os.path.relpath(file_path, dir_path) | |
- How to get only name of a file: os.path.basename(file_path) | |
Version: | |
v0.2.1 (2023-01-15) | |
https://gist.github.com/nodewee/eae12e2b74beb82162b8b488648f1fdd | |
""" | |
if not ext: | |
ext = None | |
else: | |
if not isinstance(ext, list): | |
raise TypeError("ext must be a list or None") | |
for f in os.scandir(dir): | |
if excludes: | |
is_ignore = False | |
for pat in excludes: | |
if re.search(pat, f.name): | |
is_ignore = True | |
break | |
if is_ignore: | |
continue | |
if recursive: | |
if f.is_dir(): | |
for item in list_files(f.path, ext, recursive, excludes): | |
yield item | |
if f.is_file(): | |
if ext is None: | |
yield f.path | |
else: | |
if os.path.splitext(f.name)[1].lower() in ext: | |
yield f.path |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment