Skip to content

Instantly share code, notes, and snippets.

@danjgale
Created November 18, 2020 00:10
Show Gist options
  • Save danjgale/48e1415c88eca744a32c2e52dd7adb82 to your computer and use it in GitHub Desktop.
Save danjgale/48e1415c88eca744a32c2e52dd7adb82 to your computer and use it in GitHub Desktop.
Super handy awesome cool neat function to get files using a glob pattern.
import os
import natsort
import glob
def get_files(pattern, force_list=False):
"""Extracts files in alphanumerical order that match the provided glob
pattern.
Parameters
----------
pattern : str or list
Glob pattern or a list of strings that will be joined together to form
a single glob pattern.
force_list : bool, optional
Force output to be a list. If False (default), a string is returned in
cases where only one file is detected.
Returns
-------
str or list
Detected file(s).
Raises
------
FileNotFoundError
No files were detected using the input pattern.
"""
if isinstance(pattern, list):
pattern = os.path.join(*pattern)
files = natsort.natsorted(glob.glob(pattern))
if not files:
raise FileNotFoundError('Pattern could not detect file(s)')
if force_list:
return files
else:
return files[0] if len(files) == 1 else files
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment