简体   繁体   English

在目录和子目录中找到所有文件,并提供目录的路径

[英]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.

相关问题 Python代码,用于从/ directory开始查找所有目录/子目录中新创建,修改和删除的文件 - Python code to find all newly created, modified and deleted files in all the directories/sub-directories starting from / directory 如何删除目录中的所有文件,并保持子目录完整 - How to delete all files in a directory, keeping sub-directories intact 只要子目录名称匹配,就将文件从一个目录和子目录复制到另一个目录 - Copying files from one directory, and sub-directories, to another, so long as sub-directory names match 如何在特定目录(包括其子目录)中列出所有文件及其大小和创建日期? - How can I list all files with their sizes and date of creation in a specific directory including its sub-directories? 在特定目录及其子目录中,找到所有扩展名为.tmp的文件夹 - In a particular directory and its sub-directories, find all the folders ending with .tmp extension glob.iglob查找所有子目录中的所有.txt文件会产生错误 - glob.iglob to find all .txt files in all sub-directories yields error 调整目录所有子目录中所有图像的大小 - Resize all images in all sub-directories of directory 仅在目录,子目录中读取最近2个月的文件 - Read files for last 2 months only in directory, sub-directories 通过 python 从目录及其子目录中的 txt/srt 文件中删除特定的空白行 - Removing specific blank lines from txt/srt files inside a directory and its sub-directories by python 尝试列出目录的所有子目录时键入错误 - Type error when trying to list all the sub-directories of a directory
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM