如何在Python中迭代给定目录中的文件?

如何在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']

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程