Computer >> Máy Tính >  >> Lập trình >> Python

Làm cách nào để bạn có được danh sách thư mục được sắp xếp theo ngày tạo trong Python?


Để nhận danh sách thư mục được sắp xếp theo ngày tạo trong Python, bạn có thể gọi os.listdir () để nhận danh sách tên tệp. Sau đó gọi os.stat () cho từng cái để lấy thời gian tạo và cuối cùng sắp xếp theo thời gian tạo.

ví dụ

import os
import time
import sys
from stat import S_ISREG, ST_CTIME, ST_MODE
dir_path = '.'
# get all entries in the directory
entries = (os.path.join(dir_path, file_name) for file_name in os.listdir(dir_path))
# Get their stats
entries = ((os.stat(path), path) for path in entries)
# leave only regular files, insert creation date
entries = ((stat[ST_CTIME], path)
           for stat, path in entries if S_ISREG(stat[ST_MODE]))
print(entries)

Đầu ra

Chạy mã trên sẽ cung cấp cho bạn danh sách được sắp xếp theo ngày tạo, ví dụ:

Mon Oct 23 18:01:25 2017 sorted_ls.py