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


当前回答

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

import os

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

其他回答

你可以使用

os.listdir(path)

参考和更多的操作系统函数看这里:

Python 2文档:https://docs.python.org/2/library/os.html#os.listdir Python 3文档:https://docs.python.org/3/library/os.html#os.listdir

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

import os

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

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

对于当前工作目录中的文件,无需指定路径

Python 2.7:

import os
os.listdir('.')

Python 3. x:

import os
os.listdir()

我写了一个很长的版本,包含了我可能需要的所有选项:http://sam.nipl.net/code/python/find.py

我想它也适合这里:

#!/usr/bin/env python

import os
import sys

def ls(dir, hidden=False, relative=True):
    nodes = []
    for nm in os.listdir(dir):
        if not hidden and nm.startswith('.'):
            continue
        if not relative:
            nm = os.path.join(dir, nm)
        nodes.append(nm)
    nodes.sort()
    return nodes

def find(root, files=True, dirs=False, hidden=False, relative=True, topdown=True):
    root = os.path.join(root, '')  # add slash if not there
    for parent, ldirs, lfiles in os.walk(root, topdown=topdown):
        if relative:
            parent = parent[len(root):]
        if dirs and parent:
            yield os.path.join(parent, '')
        if not hidden:
            lfiles   = [nm for nm in lfiles if not nm.startswith('.')]
            ldirs[:] = [nm for nm in ldirs  if not nm.startswith('.')]  # in place
        if files:
            lfiles.sort()
            for nm in lfiles:
                nm = os.path.join(parent, nm)
                yield nm

def test(root):
    print "* directory listing, with hidden files:"
    print ls(root, hidden=True)
    print
    print "* recursive listing, with dirs, but no hidden files:"
    for f in find(root, dirs=True):
        print f
    print

if __name__ == "__main__":
    test(*sys.argv[1:])

这是另一种选择。

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文档