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

Làm cách nào để tôi có thể lặp lại các tệp trong một thư mục nhất định 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. 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']

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']