Search code examples
pythonglobpathlib

Retrieve latest file with pathlib


I primarily use pathlib over os for paths, however there is one thing I have failed to get working on pathlib. If for example I require the latest created .csv within a directory I would use glob & os

import glob
import os

target_dir = glob.glob("/home/foo/bar/baz/*.csv")
latest_csv = max(target_dir, key=os.path.getctime)

Is there an alternative using pathlib only? (I am aware you can yield matching files with Path.glob(*.csv))


Solution

  • You can achieve it in just pathlib by doing the following:

    A Path object has a method called stat() where you can retrieve things like creation and modify date.

    from pathlib import Path
    
    files = Path("./").glob("*.py")
    
    latest_file = max([f for f in files], key=lambda item: item.stat().st_ctime)
    
    print(latest_file)