【问题标题】:Following a nested directory structure until the end遵循嵌套目录结构直到结束
【发布时间】:2012-10-11 07:23:05
【问题描述】:

我有一些目录,其中包含一些其他目录,这些目录在最低级别包含一堆 csv 文件,例如(文件夹)a -> b -> c ->(csv 文件)。每一层通常只有一个文件夹。当我处理一个目录时,我如何才能遵循这个结构直到最后得到 csv 文件?我在想也许是一个递归解决方案,但我认为可能有更好的方法来做到这一点。我正在使用python。希望我是清楚的。

【问题讨论】:

    标签: python directory


    【解决方案1】:

    os 包有一个 walk 函数,可以完全满足您的需要:

    for current_path, directory, files in walk("/some/path"):
        # current_path is the full path of the directory we are currently in
        # directory is the name of the directory
        # files is a list of file names in this directory
    

    您可以使用os.path's 导出每个文件的完整路径(如果需要)。

    或者,您可能会发现 glob 模块对您更有用:

    for csv_file in glob(/some/path/*/*.csv"):
        # csv_file is the full path to the csv file.
    

    【讨论】:

      猜你喜欢
      • 2022-01-26
      • 2015-06-30
      • 1970-01-01
      • 2014-06-26
      • 1970-01-01
      • 1970-01-01
      • 2012-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多