我如何在Python中获得给定目录中的所有文件(和目录)的列表?


当前回答

这是另一种选择。

os.scandir(path='.')

它返回os的迭代器。对应于path指定目录中的条目(以及文件属性信息)的DirEntry对象。

例子:

with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.'):
            print(entry.name)

Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type or file attribute information, because os.DirEntry objects expose this information if the operating system provides it when scanning a directory. All os.DirEntry methods may perform a system call, but is_dir() and is_file() usually only require a system call for symbolic links; os.DirEntry.stat() always requires a system call on Unix but only requires one for symbolic links on Windows.

Python文档

其他回答

对于Python 2

#!/bin/python2

import os

def scan_dir(path):
    print map(os.path.abspath, os.listdir(pwd))

对于Python 3

对于filter和map,你需要用list()来包装它们

#!/bin/python3

import os

def scan_dir(path):
    print(list(map(os.path.abspath, os.listdir(pwd))))

现在的建议是用生成器表达式或列表推导式替换map和filter的使用:

#!/bin/python

import os

def scan_dir(path):
    print([os.path.abspath(f) for f in os.listdir(path)])

只递归列出文件的漂亮的一行代码。我在setup.py package_data指令中使用了这个:

import os

[os.path.join(x[0],y) for x in os.walk('<some_directory>') for y in x[2]]

我知道这不是问题的答案,但可能会派上用场

这是另一种选择。

os.scandir(path='.')

它返回os的迭代器。对应于path指定目录中的条目(以及文件属性信息)的DirEntry对象。

例子:

with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.'):
            print(entry.name)

Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type or file attribute information, because os.DirEntry objects expose this information if the operating system provides it when scanning a directory. All os.DirEntry methods may perform a system call, but is_dir() and is_file() usually only require a system call for symbolic links; os.DirEntry.stat() always requires a system call on Unix but only requires one for symbolic links on Windows.

Python文档

如果你需要通配符,也有一个模块。例如:

import glob
glob.glob('./[0-9].*')

将返回如下内容:

['./1.gif', './2.txt']

请在这里查看文档。

下面是我经常使用的一个辅助函数:

import os

def listdir_fullpath(d):
    return [os.path.join(d, f) for f in os.listdir(d)]