get_file_paths

pyhelpers.dirs.get_file_paths(dir_path, file_ext=None, incl_subdir=False, abs_path=False, normalized=True, prepend_dot=False)[source]

Get the paths of files in a directory, optionally filtered by file extension.

This function retrieves paths of files within the directory specified by dir_path. Files are optionally filtered by the exact file_ext given, matched against each file’s actual extension (via os.path.splitext) rather than a trailing-substring comparison. If file_ext is None, "*" or "all", all files are returned. If incl_subdir=True, subdirectories are traversed recursively.

Parameters:
  • dir_path (str | os.PathLike) – Pathname of the directory to search.

  • file_ext (str | None) – Exact file extension to filter files by, with or without the leading dot (e.g. ".txt" or "txt"). Defaults to None, in which case all files are returned regardless of extension.

  • incl_subdir (bool) – Whether to include files from subdirectories; when incl_subdir=True, files from all subdirectories are included recursively. Defaults to False.

  • abs_path (bool) – Whether to return absolute pathname(s). Defaults to False.

  • normalized (bool) – Whether to normalize the returned pathname(s) via _normalize_path(). Defaults to True.

  • prepend_dot (bool) – If True, prepends "./" to a relative pathname that doesn’t already have a dot-relative or absolute prefix. Only takes effect when normalized=True. Defaults to False.

Returns:

List of file pathnames matching the criteria.

Return type:

list[str]

Examples:

>>> from pyhelpers.dirs import get_file_paths, delete_dir
>>> from pyhelpers.store import unzip
>>> import os

>>> test_dir_name = "tests/data"

>>> # Get all files in the directory (without subdirectories) on Windows
>>> get_file_paths(test_dir_name, prepend_dot=True)
['./tests/data/csr_mat.npz',
 './tests/data/dat.csv',
 './tests/data/dat.feather',
 './tests/data/dat.joblib',
 './tests/data/dat.json',
 './tests/data/dat.ods',
 './tests/data/dat.pickle',
 './tests/data/dat.pickle.bz2',
 './tests/data/dat.pickle.gz',
 './tests/data/dat.pickle.xz',
 './tests/data/dat.txt',
 './tests/data/dat.xlsx',
 './tests/data/zipped.7z',
 './tests/data/zipped.txt',
 './tests/data/zipped.zip']

>>> get_file_paths(test_dir_name, file_ext=".txt")
['tests/data/dat.txt', 'tests/data/zipped.txt']

>>> output_dir = unzip('tests/data/zipped.zip', ret_output_dir=True)
>>> os.listdir(output_dir)
['zipped.txt']

>>> # Get absolute paths of all files contained in the folder (incl. all subdirectories)
>>> get_file_paths(test_dir_name, file_ext="txt", incl_subdir=True, abs_path=True)
['<Parent directories>/tests/data/dat.txt',
 '<Parent directories>/tests/data/zipped.txt',
 '<Parent directories>/tests/data/zipped/zipped.txt']

>>> delete_dir(output_dir, confirmation_required=False, verbose=True)
Deleting "tests/data/zipped/" ... Done.