Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Liệt kê thư mục sắp xếp theo ngày tạo trong Python

Dùng os.stat() lấy st_ctime (creation time Windows, metadata change Unix), sắp xếp theo giá trị này.

Ví dụ

import os
from stat import S_ISREG, ST_CTIME, ST_MODE

dir_path = '.'
entries = (os.path.join(dir_path, fn) for fn in os.listdir(dir_path))
entries = ((os.stat(p), p) for p in entries)
# Chỉ regular file, lấy (ctime, path)
entries = ((st[ST_CTIME], p) for st, p in entries if S_ISREG(st[ST_MODE]))

for ctime, path in sorted(entries):
    print(time.ctime(ctime), os.path.basename(path))

Kết quả mẫu

Mon Oct 23 18:01:25 2017 sorted_ls.py
Tue Oct 24 09:15:00 2017 data.csv
...

Đơn giản hơn (pathlib, Python 3.10+)

from pathlib import Path
files = [f for f in Path('.').iterdir() if f.is_file()]
for f in sorted(files, key=lambda p: p.stat().st_ctime):
    print(f.stat().st_ctime, f.name)

Lưu ý: Trên Unix, st_ctime là metadata change time, không phải creation time (birth time). Dùng st_birthtime (macOS/BSD) hoặc statx (Linux 4.11+) cho birth time thật.