Python列表目录,子目录和文件

我试图做一个脚本来列出给定目录中的所有目录,子目录和文件。
我试过这个:

import sys,os root = "/home/patate/directory/" path = os.path.join(root, "targetdirectory") for r,d,f in os.walk(path): for file in f: print os.path.join(root,file) 

不幸的是它不能正常工作。
我得到所有的文件,但没有完整的path。

例如,如果dir结构将是:

 /home/patate/directory/targetdirectory/123/456/789/file.txt

它会打印:

 /home/patate/directory/targetdirectory/file.txt

我需要的是第一个结果。 任何帮助将不胜感激! 谢谢。

使用os.path.join连接目录和文件

 for path, subdirs, files in os.walk(root): for name in files: print os.path.join(path, name) 

注意在连接中使用path而不使用root ,因为使用root将是不正确的。


在Python 3.4中,添加了pathlib模块以实现更简单的path操作。 所以相当于os.path.join将是:

 pathlib.PurePath(path, name) 

pathlib的优点是你可以在path上使用各种有用的方法。 如果您使用具体的Path变体,您也可以通过它们进行实际的操作系统调用,比如追加到目录,删除path,打开指向的文件等等。

以防万一…获取目录中的所有文件和与某些模式匹配的子目录(例如* .py):

 import os from fnmatch import fnmatch root = '/some/directory' pattern = "*.py" for path, subdirs, files in os.walk(root): for name in files: if fnmatch(name, pattern): print os.path.join(path, name) 

你应该在你的连接中使用'r'而不是'root'

这是一个单行的:

 import os [val for sublist in [[os.path.join(i[0], j) for j in i[2]] for i in os.walk('./')] for val in sublist] # Meta comment to ease selecting text 

val for sublist in ...最外层val for sublist in ...平整为一维。 j循环收集每个文件基本名称的列表,并将其连接到当前path。 最后, i循环遍历所有目录和子目录。

此示例在os.walk(...)调用中使用硬编码path./ ,可以补充您喜欢的任何pathstring。

注意: os.path.expanduser和/或os.path.expandvars可用于pathstring,如~/

扩展这个例子:

它很容易添加在文件基本名称testing和目录名称testing。

例如,testing*.jpg文件:

 ... for j in i[2] if j.endswith('.jpg')] ... 

另外,不包括.git目录:

 ... for i in os.walk('./') if '.git' not in i[0].split('/')] 

你可以看看我制作的这个样本。 它使用os.path.walk函数,不build议使用。要使用列表来存储所有的文件path

 root = "Your root directory" ex = ".txt" where_to = "Wherever you wanna write your file to" def fileWalker(ext,dirname,names): ''' checks files in names''' pat = "*" + ext[0] for f in names: if fnmatch.fnmatch(f,pat): ext[1].append(os.path.join(dirname,f)) def writeTo(fList): with open(where_to,"w") as f: for di_r in fList: f.write(di_r + "\n") if __name__ == '__main__': li = [] os.path.walk(root,fileWalker,[ex,li]) writeTo(li)