4

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

DECROMAX
  • 194
  • 3
  • 13

1 Answers1

7

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)
Richard
  • 416
  • 4
  • 13
  • A simplification in syntax is to replace `[f for f in files]` with `list(files)`. see https://stackoverflow.com/questions/3790848/fastest-way-to-convert-an-iterator-to-a-list/64512225#64512225 – wisbucky Oct 06 '22 at 18:31
  • 2
    `max` takes any iterable, so you don't even need to convert it into a list first. `max(files, key=...)` should work just as well. – Petzku May 31 '23 at 22:34