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 tên trong Python

Dùng sorted(os.listdir(path), key=str.lower) cho case-insensitive alphabetical order.

Ví dụ

import os

entries = os.listdir('.')
for entry in sorted(entries, key=str.lower):
    print(entry)

Kết quả mẫu

dlls
doc
etc
include
lib
libs
license.txt
news.txt
python.exe
pythonw.exe
readme.txt
scripts
share
tcl
tools
w9xpopen.exe

Sắp xếp theo tiêu chí khác

# Theo size (file)
sorted(os.listdir('.'), key=lambda f: os.path.getsize(f) if os.path.isfile(f) else -1)

# Theo modification time
sorted(os.listdir('.'), key=lambda f: os.path.getmtime(f))