Home > Net >  Retrieve latest file with pathlib
Retrieve latest file with pathlib

Time:03-05

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))

CodePudding user response:

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)
  • Related