我试图使一个脚本列出所有目录,子目录,和文件在一个给定的目录。
我试了一下:
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))
不幸的是,它不能正常工作。
我得到了所有文件,但没有它们的完整路径。
例如,如果dir结构体为:
/home/patate/directory/targetdirectory/123/456/789/file.txt
它将打印:
/home/patate/directory/targetdirectory/file.txt
我需要的是第一个结果。任何帮助都将不胜感激!谢谢。
你可以看看我做的这个样品。它使用os.path.walk函数,该函数已被弃用。使用列表存储所有文件路径
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)
下面是一行代码:
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…循环将列表平展为一维。j循环收集每个文件basename的列表,并将其连接到当前路径。最后,i循环遍历所有目录和子目录。
这个例子在os.walk(…)调用中使用了硬编码的路径。/,你可以补充任何你喜欢的路径字符串。
注意:os.path.expanduser和/或os.path.expandvars可以用于~/这样的路径字符串
扩展这个例子:
很容易在文件basename测试和directoryname测试中添加。
例如,测试*.jpg文件:
... for j in i[2] if j.endswith('.jpg')] ...
此外,不包括.git目录:
... for i in os.walk('./') if '.git' not in i[0].split('/')]