python中的目录列表

时间:2011-07-15 11:08:00

标签: python directory

我遇到了目录列表的问题。假设,我有一个带有一些子目录的目录(名为a-z,0-9,%, - )。在每个子目录中,我都有一些相关的xml文件。 所以,我必须阅读这些文件的每一行。我尝试使用以下代码。

def listFilesMain(dirpath):
    for dirname, dirnames, filenames in os.walk(dirpath):
        for subdirname in dirnames:
            os.path.join(dirname, subdirname)
        for filename in filenames:
            fPath = os.path.join(dirname, filename)
            fileListMain.append(fPath)

只有当我尝试从子目录运行我的程序时它才有效,但如果我试图从主目录运行则没有结果。这里出了什么问题? 任何形式的帮助将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:2)

这个怎么样:

def list_files(dirpath):
    files = []
    for dirname, dirnames, filenames in os.walk(dirpath):
        files += [os.path.join(dirname, filename) for filename in filenames]
    return files

您也可以将此作为生成器执行此操作,因此列表不会完整存储:

def list_files(dirpath):
    for dirname, dirnames, filenames in os.walk(dirpath):
        for filename in filenames:
            yield os.path.join(dirname, filename)

最后,您可能希望强制执行绝对路径:

def list_files(dirpath):
    dirpath = os.path.abspath(dirpath)
    for dirname, dirnames, filenames in os.walk(dirpath):
        for filename in filenames:
            yield os.path.join(dirname, filename)

所有这些都可以通过如下行来调用:

for filePath in list_files(dirpath):
    # Check that the file is an XML file.
    # Then handle the file.

答案 1 :(得分:1)

如果您的子目录是软链接,请确保将followlinks=True指定为os.walk(..)的参数。来自文档:

    By default, os.walk does not follow symbolic links to subdirectories on
    systems that support them.  In order to get this functionality, set the
    optional argument 'followlinks' to true.