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

Làm cách nào để liệt kê tất cả các tệp theo thứ tự bảng chữ cái bằng Python?

Bạn có thể gọi hàm os.listdir để lấy danh sách nội dung thư mục và sử dụng hàm đã sắp xếp để sắp xếp danh sách này.

Ví dụ

>>> import os
>>> list_dir = os.listdir('.')
>>> list_dir = [f.lower() for f in list_dir]   # Convert to lower case
>>> sorted(list_dir)
['dlls', 'doc', 'etc', 'include', 'lib', 'libs', 'license.txt', 'news.txt', 'python.exe', 'pythonw.exe', 'readme.txt', 'scripts', 'share', 'tcl', 'tools', 'w9xpopen.exe']