如何在Python中列出目录中的所有文件?
os.listdir(my_path)会将my_path目录中的所有内容(包括文件和目录)列出。
更多Python相关文章,请阅读:Python 教程
示例
您可以按以下方式使用它:
>>> 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']
极客教程