使用pathlib检索最新文件

发布于 2025-01-11 15:52:43 字数 323 浏览 3 评论 0原文

我主要使用 pathlib 而不是 os 作为路径,但是有一件事我未能在 pathlib 上工作。 例如,如果我需要目录中最新创建的 .csv,我将使用 glob & os

import glob
import os

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

有没有仅使用 pathlib 的替代方案? (我知道您可以使用 Path.glob(*.csv) 生成匹配文件)

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

叫嚣ゝ 2025-01-18 15:52:43

您可以通过执行以下操作在 pathlib 中实现它:

Path 对象有一个名为 stat() 的方法,您可以在其中检索创建和修改日期等内容。

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)

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文