如何遍历Python给定目录中的文件?

os.listdir(my_path)将为您提供my_path目录中的所有内容-文件和目录。您可以按以下方式使用它:

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

如果只需要文件,则可以使用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']