【问题标题】:find all files indirectory and sub-directories and provide the path from directory查找所有文件目录和子目录并提供目录中的路径
【发布时间】:2015-11-12 21:32:33
【问题描述】:

您好,我想查找文件夹中的所有文件,包括子文件夹中的所有文件。这是我的代码

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

但是,上面的代码为我提供了包含完整路径的所有文件。我想要所有具有根路径的文件。因此,如果文件在根目录中,我只想要文件名,如果它在子目录根/图像中,我想要图像/文件名.. 谢谢卡尔

【问题讨论】:

    标签: python


    【解决方案1】:

    改变:

    all_files.append(os.path.join(path, name))
    

    到:

    all_files.append(os.path.join(path[len(root):], name))
    

    从根的长度开始对当前路径进行切片。即:

    >>> root = 'hello'
    >>> sub = 'hello is is ew'
    >>> sub[:len(root)]
    'hello'
    >>> sub[len(root):]
    ' is is ew'
    

    你也可以使用relpath()

    >>> os.path.relpath('root/image/thistoo','root')
    'image\\thistoo'
    

    所以:

    all_files.append(os.path.join(os.path.relpath(path,root), name))
    

    【讨论】:

    • @Pynchia 我不敢苟同,所有 python strip 方法都将参数读取为字符列表,因此它将从字符串的开头删除这些字符的所有实例。即如果你打电话给'root/hey/heyo/rooted'.lstrip('root/hey'),你会得到'd'的返回值
    猜你喜欢
    • 1970-01-01
    • 2013-03-20
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    • 1970-01-01
    • 2015-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多