Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

คุณจะได้รับรายชื่อไดเรกทอรีที่จัดเรียงตามวันที่สร้างใน Python ได้อย่างไร


หากต้องการรับรายการไดเรกทอรีที่จัดเรียงตามวันที่สร้างใน Python คุณสามารถเรียก os.listdir() เพื่อรับรายชื่อไฟล์ จากนั้นเรียก os.stat() สำหรับแต่ละอันเพื่อรับเวลาสร้างและสุดท้ายเรียงลำดับตามเวลาที่สร้าง

ตัวอย่าง

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)

ผลลัพธ์

การรันโค้ดด้านบนจะทำให้คุณมีรายชื่อเรียงตามวันที่สร้าง เช่น

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