get_file_in_dir#

get_file_in_dir(directory: Union[str, cloudpathlib.cloudpath.CloudPath, pathlib.Path], pattern_str: str, extension: Optional[str] = None, filename_only: bool = False, get_list: bool = False, exact_name: bool = False) Union[cloudpathlib.cloudpath.CloudPath, pathlib.Path, list][source]#

Get one or all matching files (pattern + extension) from inside a directory.

Note that the pattern is a regex with glob’s convention, ie. *pattern*.

If exact_name is False, the searched pattern will be *{pattern}*.{extension}, else {pattern}.{extension}.

>>> directory = 'D:/path/to/dir'
>>> os.listdir(directory)
["haha.txt", "huhu1.txt", "huhu1.geojson", "hoho.txt"]

>>> get_file_in_dir(directory, "huhu")
'D:/path/to/dir/huhu1.geojson'

>>> get_file_in_dir(directory, "huhu", extension="txt")
'D:/path/to/dir/huhu1.txt'

>>> get_file_in_dir(directory, "huhu", get_list=True)
['D:/path/to/dir/huhu1.txt', 'D:/path/to/dir/huhu1.geojson']

>>> get_file_in_dir(directory, "huhu", filename_only=True, get_list=True)
['huhu1.txt', 'huhu1.geojson']

>>> get_file_in_dir(directory, "huhu", get_list=True, exact_name=True)
[]
Parameters
  • directory (str) – Directory where to find the files

  • pattern_str (str) – Pattern wanted as a string, with glob’s convention.

  • extension (str) – Extension wanted, optional. With or without point. (yaml or .yaml accepted)

  • filename_only (bool) – Get only the filename

  • get_list (bool) – Get the whole list of matching files

  • exact_name (bool) – Get the exact name (without adding * before and after the given pattern)

Returns

File

Return type

Union[CloudPath, Path, list]