【问题标题】:Python 2.7 How to list files in a directory AND all sub directories?Python 2.7 如何列出目录和所有子目录中的文件?
【发布时间】:2014-10-16 10:38:04
【问题描述】:

我正在编写一个脚本,列出车道数、文本文件中的单词,现在我想添加查找重复项。

现在我正在使用它来列出目录中的所有文本文件:

from sys import argv 
script, directory - argv
files = glob.glob(directory + "/*.txt")

如果目录中有任何子文件夹,则不会列出这些文件。我该怎么做才能列出所有子目录中的所有文件?

【问题讨论】:

    标签: python python-2.7 directory


    【解决方案1】:

    你可以使用os.walk。

    files = [f for (dir, subdirs, fs) in os.walk(directory) for f in fs if f.endswith(".txt")]
    

    【讨论】:

      【解决方案2】:

      你可以看到 Python recursive folder read

      和

      Use a Glob() to find files recursively in Python?

      这些是有用的帖子,有解决方案和很好的解释

      【讨论】:

        猜你喜欢
        • 2012-11-14
        • 2012-09-02
        • 2016-01-16
        • 1970-01-01
        • 2011-02-23
        • 2011-03-01
        • 1970-01-01
        相关资源
        最近更新 更多