【问题标题】:In python, how to get the path to all the files in a directory, including files in subdirectories, but excluding path to subdirectories在python中,如何获取目录中所有文件的路径,包括子目录中的文件,但不包括子目录的路径
【发布时间】:2016-01-17 16:52:40
【问题描述】:

我有一个包含文件夹和子文件夹的目录。每个路径的末尾都有文件。我想制作一个 txt 文件,其中包含所有文件的路径,但不包括文件夹的路径。

我尝试了Getting a list of all subdirectories in the current directory 的这个建议,我的代码如下所示:

import os

myDir = '/path/somewhere'

print [x[0] for x in os.walk(myDir)] 

它给出了所有元素(文件和文件夹)的路径,但我只想要文件的路径。有什么想法吗?

【问题讨论】:

  • 您可以将根目录与os.walk中的文件名连接起来。

标签: python path os.walk


【解决方案1】:

os.walk 方法会在每次迭代中为您提供目录、子目录和文件,因此当您在 os.walk 中循环时,您将不得不遍历文件并将每个文件与“dir”组合起来。

为了执行这种组合,您要做的是在目录和文件之间做一个os.path.join

这里有一个简单的例子来帮助说明如何使用 os.walk 进行遍历

from os import walk
from os.path import join

# specify in your loop in order dir, subdirectory, file for each level
for dir, subdir, files in walk('path'):
    # iterate over each file
    for file in files:
        # join will put together the directory and the file
        print(join(dir, file))

【讨论】:

    【解决方案2】:

    os.walk(path) 返回三个元组父文件夹、子目录和文件。

    所以你可以这样做:

    for dir, subdir, files in os.walk(path):
        for file in files:
            print os.path.join(dir, file)
    

    【讨论】:

    • 这项工作,谢谢。稍微说明一下,第一行代码应该是for dir, subdir, files in os.walk(path):
    • @mcrash 感谢您的通知,输入错误,现在更新
    【解决方案3】:

    如果您只想要路径,请在列表理解中添加一个过滤器,如下所示:

    import os
    
    myDir = '/path/somewhere'
    print [dirpath for dirpath, dirnames, filenames in os.walk(myDir) if filenames] 
    

    这只会添加包含文件的文件夹的路径。

    【讨论】:

    • 你只打印非空目录的路径,Op也想要所有文件的路径
    【解决方案4】:
    def get_paths(path, depth=None):
        for name in os.listdir(path):
            full_path = os.path.join(path, name)
    
            if os.path.isfile(full_path):
                yield full_path
    
            else:
                d = depth - 1 if depth is not None else None
    
                if d is None or d >= 0:
                    for sub_path in get_paths(full_path):
                        yield sub_path
    

    【讨论】:

      猜你喜欢
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      • 2010-12-09
      • 2013-11-12
      • 1970-01-01
      • 1970-01-01
      • 2013-08-09
      • 2015-12-07
      相关资源
      最近更新 更多