Python中的目录列表

如何获得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) 

为了参考和更多的osfunction看这里:

  • 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 for filename in os.listdir("C:\\temp"): print filename 

这是我经常使用的帮助函数:

 import os def listdir_fullpath(d): return [os.path.join(d, f) for f in os.listdir(d)] 

如果你需要通配能力,那么也有一个模块。 例如:

 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) 

recursion实现

 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) 

对于当前工作目录中的文件,不指定path

Python 2.7:

 import os os.listdir(os.getcwd()) 

Python 3.x:

 import os os.listdir() 

感谢Stam Kaly对python 3.x的评论

我写了一个长版本,我可能需要的所有选项: http : //sam.nipl.net/code/python/find.py

我想这也适合在这里:

 #!/usr/bin/env python import os import sys def ls(dir, hidden=False, relative=True): nodes = [] for nm in os.listdir(dir): if not hidden and nm.startswith('.'): continue if not relative: nm = os.path.join(dir, nm) nodes.append(nm) nodes.sort() return nodes def find(root, files=True, dirs=False, hidden=False, relative=True, topdown=True): root = os.path.join(root, '') # add slash if not there for parent, ldirs, lfiles in os.walk(root, topdown=topdown): if relative: parent = parent[len(root):] if dirs and parent: yield os.path.join(parent, '') if not hidden: lfiles = [nm for nm in lfiles if not nm.startswith('.')] ldirs[:] = [nm for nm in ldirs if not nm.startswith('.')] # in place if files: lfiles.sort() for nm in lfiles: nm = os.path.join(parent, nm) yield nm def test(root): print "* directory listing, with hidden files:" print ls(root, hidden=True) print print "* recursive listing, with dirs, but no hidden files:" for f in find(root, dirs=True): print f print if __name__ == "__main__": test(*sys.argv[1:]) 

一个很好的class轮只列出文件recursion。 我在我的setup.py package_data指令中使用了这个:

 import os [os.path.join(x[0],y) for x in os.walk('<some_directory>') for y in x[2]] 

我知道这不是问题的答案,但可能派上用场

对于Python 2

 #!/bin/python2 import os def scan_dir(path): print map(os.path.abspath, os.listdir(pwd)) 

对于Python 3

对于filter和地图,你需要用list()

 #!/bin/python3 import os def scan_dir(path): print(list(map(os.path.abspath, os.listdir(pwd)))) 

现在的build议是,您用生成器expression式或列表parsing来replace您的映射和filter的使用:

 #!/bin/python import os def scan_dir(path): print([os.path.abspath(f) for f in os.listdir(path)]) 
 #import modules import os _CURRENT_DIR = '.' def rec_tree_traverse(curr_dir, indent): "recurcive function to traverse the directory" #print "[traverse_tree]" try : dfList = [os.path.join(curr_dir, f_or_d) for f_or_d in os.listdir(curr_dir)] except: print "wrong path name/directory name" return for file_or_dir in dfList: if os.path.isdir(file_or_dir): #print "dir : ", print indent, file_or_dir,"\\" rec_tree_traverse(file_or_dir, indent*2) if os.path.isfile(file_or_dir): #print "file : ", print indent, file_or_dir #end if for loop #end of traverse_tree() def main(): base_dir = _CURRENT_DIR rec_tree_traverse(base_dir," ") raw_input("enter any key to exit....") #end of main() if __name__ == '__main__': main() 

仅供参考添加扩展或ext文件导入操作系统的filter

 path = '.' for dirname, dirnames, filenames in os.walk(path): # print path to all filenames with extension py. for filename in filenames: fname_path = os.path.join(dirname, filename) fext = os.path.splitext(fname_path)[1] if fext == '.py': print fname_path else: continue 
 import os, sys #open files in directory path = "My Documents" dirs = os.listdir( path ) # print the files in given directory for file in dirs: print (file) 

如果能算出来,我会把它扔进去。简单而肮脏的方法来做通配符search。

 import re import os [a for a in os.listdir(".") if re.search("^.*\.py$",a)] 

下面的代码将列出dir中的目录和文件

 def print_directory_contents(sPath): import os for sChild in os.listdir(sPath): sChildPath = os.path.join(sPath,sChild) if os.path.isdir(sChildPath): print_directory_contents(sChildPath) else: print(sChildPath) 

这里是一个Pythonic版本:

 import os dir = 'given_directory_name' filenames = [os.path.join(os.path.dirname(os.path.abspath(__file__)),dir,i) for i in os.listdir(dir)] 

此代码列出给定目录名称中所有文件和目录的完整path。

我知道这是一个古老的问题。 如果你是在一台liunx机器上,这是一个很好的方式。

 import subprocess print(subprocess.check_output(["ls", "/"]).decode("utf8"))