如何获取Python中给定目录中所有文件(和目录)的列表?
这是遍历目录树中每个文件和目录的方法:
import os for dirname, dirnames, filenames in os.walk('.'): # print path to all subdirectories first. for subdirname in dirnames: print(os.path.join(dirname, subdirname)) # print path to all filenames. for filename in filenames: print(os.path.join(dirname, filename)) # Advanced usage: # editing the 'dirnames' list will stop os.walk() from recursing into there. if '.git' in dirnames: # don't go into any .git directories. dirnames.remove('.git')
您可以使用
os.listdir(path)
有关参考和更多os函数,请在此处查看:
Python 2文档:https://docs.python.org/2/library/os.html#os.listdir
Python 3文档:https://docs.python.org/3/library/os.html#os.listdir
这是我经常使用的辅助函数:
import os def listdir_fullpath(d): return [os.path.join(d, f) for f in os.listdir(d)]
import os for filename in os.listdir("C:\\temp"): print filename
如果你需要通配能力,那么也有一个模块.例如:
import glob glob.glob('./[0-9].*')
将返回如下内容:
['./1.gif', './2.txt']
请参阅此处的文档.
试试这个:
import os for top, dirs, files in os.walk('./'): for nm in files: print os.path.join(top, nm)
对于当前工作目录中的文件而不指定路径
Python 2.7:
import os os.listdir(os.getcwd())
Python 3.x:
import os os.listdir()
感谢Stam Kaly对python 3.x的评论
递归实现
import os def scan_dir(dir): for name in os.listdir(dir): path = os.path.join(dir, name) if os.path.isfile(path): print path else: scan_dir(path)