DECROMAX

Return latest or oldest file in directory (using pathlib)

Mar 5th, 2022 (edited)
315
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.39 KB | None | 0 0
  1. from pathlib import Path # (glob import not required)
  2.  
  3. # can replace max for min for oldest file
  4.  
  5. def latest_file(dir_path: str, file_ext=".csv") -> Path:
  6.     """returns most recent file
  7.    arg 1: dir path, arg 2: file ext (default .csv)"""
  8.     str_path = Path(dir_path).glob(f"*{file_ext}")
  9.     latest_file = max(str_path, key=lambda item: item.stat().st_ctime)
  10.     return latest_file
Add Comment
Please, Sign In to add comment