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

Liệt kê file theo thứ tự bảng chữ cái trong Python (os.listdir + sorted)

Dùng os.listdir() lấy danh sách, sorted() sắp xếp.

Ví dụ

import os

files = os.listdir('.')
files_lower = [f.lower() for f in files]  # case-insensitive sort
for f in sorted(files_lower):
    print(f)

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 giữ nguyên case (key=str.lower)

sorted(os.listdir('.'), key=str.lower)

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

# Theo kích thước
sorted(os.listdir('.'), key=lambda f: os.path.getsize(f))

# Theo thời gian sửa đổi
sorted(os.listdir('.'), key=lambda f: os.path.getmtime(f))