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

Cách liệt kê tất cả file trong thư mục Python?


os.listdir(my_path) lấy mọi thứ trong thư mục my_path - cả file và thư mục.

Ví dụ

Dùng như sau:

>>> import os
>>> os.listdir('.')
['DLLs', 'Doc', 'etc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'pythonw.exe', 'README.txt', 'Scripts', 'share', 'tcl', 'Tools', 'w9xpopen.exe']

Kết quả

Nếu chỉ muốn file, lọc bằng isfile:

>>> import os
>>> file_list = [f for f in os.listdir('.') if os.path.isfile(os.path.join('.', f))]
>>> print(file_list)
['LICENSE.txt', 'NEWS.txt', 'python.exe', 'pythonw.exe', 'README.txt', 'w9xpopen.exe']