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

วิธีดึงรายการไดเรกทอรีเรียงลำดับตามชื่อใน Python

สามารถเรียกฟังก์ชัน os.listdir เพื่อดึงรายการเนื้อหาในไดเรกทอรี แล้วใช้ฟังก์ชัน sorted เพื่อเรียงลำดับรายการนี้

ตัวอย่าง

>>> import os
>>> list_dir = os.listdir('.')
>>> list_dir = [f.lower() for f in list_dir]  # แปลงเป็นตัวพิมพ์เล็ก
>>> 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']