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 của một thư mục bằng Python?

os.listdir (my_path) sẽ cung cấp cho bạn mọi thứ có trong thư mục my_path - tệp và thư mục.

Ví dụ

Bạn có thể sử dụng nó 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']

Đầu ra

Nếu bạn chỉ muốn các tệp, bạn có thể lọc nó bằng cách sử dụ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']