[英]find all files indirectory and sub-directories and provide the path from directory
Hi I want to find all files in a folder including all files in the sub-folders. 嗨,我想在一个文件夹中找到所有文件,包括子文件夹中的所有文件。 This is my code
这是我的代码
all_files = []
for path, subdirs, files in os.walk(root):
for name in files:
all_files.append(os.path.join(path, name))
print "all_files2 = ", all_files
however the code above gives me all files with the entire path. 但是上面的代码为我提供了具有完整路径的所有文件。 I want all files with the path from root.
我希望所有文件都具有从根目录开始的路径。 So if the file is in root, I just want the the filename, if it is in the subdirectory root/images I want images/filename.. thanks carl
因此,如果文件位于根目录下,我只想要文件名,如果它位于子目录根目录/图像中,则我想要图像/文件名..谢谢卡尔
change: 更改:
all_files.append(os.path.join(path, name))
to: 至:
all_files.append(os.path.join(path[len(root):], name))
to slice the current path starting at how long root is. 从根的长度开始切割当前路径。 ie:
即:
>>> root = 'hello'
>>> sub = 'hello is is ew'
>>> sub[:len(root)]
'hello'
>>> sub[len(root):]
' is is ew'
you can also use relpath()
您也可以使用
relpath()
>>> os.path.relpath('root/image/thistoo','root')
'image\\thistoo'
so: 所以:
all_files.append(os.path.join(os.path.relpath(path,root), name))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.