Python中的目录树列表

Mat*_*att 559 python directory file subdirectory directory-tree

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

Jer*_*rub 610

这是遍历目录树中每个文件和目录的方法:

import os

for dirname, dirnames, filenames in os.walk('.'):
    # print path to all subdirectories first.
    for subdirname in dirnames:
        print(os.path.join(dirname, subdirname))

    # print path to all filenames.
    for filename in filenames:
        print(os.path.join(dirname, filename))

    # Advanced usage:
    # editing the 'dirnames' list will stop os.walk() from recursing into there.
    if '.git' in dirnames:
        # don't go into any .git directories.
        dirnames.remove('.git')
Run Code Online (Sandbox Code Playgroud)

  • 这将*递归*列出文件和目录 (40认同)
  • 如果从Python Shell运行此代码(按原样),请记住Ctrl + C将暂停输出到所述shell.;) (19认同)
  • @Clément"当topdown为True时,调用者可以就地修改dirnames列表(可能使用del或slice赋值),而walk()只会递归到名称保留在dirnames中的子目录;这可以用来修剪搜索,强制执行特定的访问顺序,甚至通知walk()有关调用者在再次恢复walk()之前创建或重命名的目录." 来自http://docs.python.org/2/library/os.html#os.walk (7认同)

rsl*_*ite 530

您可以使用

os.listdir(path)
Run Code Online (Sandbox Code Playgroud)

有关参考和更多os函数,请在此处查看:

  • listdir为您提供目录中唯一的文件名,是否有可用于获取完整路径的方法? (5认同)
  • @Tommy,"目录"是一个明确定义的数据结构,它指的是"ls"而不是"ls -R".此外,默认情况下,几乎所有UNIX工具都不能递归工作.我不知道提问者*意味着什么*但他*写的*是清楚的. (3认同)
  • 然而,python 3 文档告诉您使用“os.scandir”,因为在许多情况下它允许您阻止系统调用,从而提供免费的加速(IPC 和 IO 都很慢)。 (3认同)
  • 好吧,最初的问题只是模糊到不知道他们是否想要递归解决方案。“目录中的所有文件”可以解释为递归。 (2认同)

gil*_*tay 107

这是我经常使用的辅助函数:

import os

def listdir_fullpath(d):
    return [os.path.join(d, f) for f in os.listdir(d)]
Run Code Online (Sandbox Code Playgroud)

  • 发电机会更好。 (3认同)
  • 已经十年了,但是我想我是这样做的,因为os.listdir()返回一个列表并且我在模仿那个。 (3认同)
  • 有助于获得完整的路径,感谢您的把戏;) (2认同)
  • @RobertSiemer 取决于用法。在许多情况下,列表会更好,但我猜生成器更通用,因为它可以转换为列表。这取决于您是否正在寻找多功能性或更精简的东西。 (2认同)

cur*_*isk 82

import os

for filename in os.listdir("C:\\temp"):
    print  filename
Run Code Online (Sandbox Code Playgroud)

  • `r'C:\ temp'`更清晰,更喜欢"C:\\ temp"`Rawstrings比escpaing反斜杠更可取. (15认同)
  • 传递一个Unicode字符串以获取Unicode返回值. (14认同)

ken*_*nny 13

如果你需要通配能力,那么也有一个模块.例如:

import glob
glob.glob('./[0-9].*')
Run Code Online (Sandbox Code Playgroud)

将返回如下内容:

['./1.gif', './2.txt']
Run Code Online (Sandbox Code Playgroud)

请参阅此处的文档.


pax*_*blo 10

试试这个:

import os
for top, dirs, files in os.walk('./'):
    for nm in files:       
        print os.path.join(top, nm)
Run Code Online (Sandbox Code Playgroud)


Dav*_*eer 8

对于当前工作目录中的文件而不指定路径

Python 2.7:

import os
os.listdir(os.getcwd())
Run Code Online (Sandbox Code Playgroud)

Python 3.x:

import os
os.listdir()
Run Code Online (Sandbox Code Playgroud)

感谢Stam Kaly对python 3.x的评论

  • os.listdir()默认列出当前目录中的元素!因此不需要os.getcwd():) (4认同)

Ste*_*ver 7

虽然os.listdir()生成文件和目录名称列表很好,但一旦获得这些名称,您通常会想要执行更多操作 - 在 Python3 中,pathlib使其他杂务变得简单。让我们来看看,看看你是否和我一样喜欢它。

要列出 dir 内容,请构造一个 Path 对象并获取迭代器:

In [16]: Path('/etc').iterdir()
Out[16]: <generator object Path.iterdir at 0x110853fc0>
Run Code Online (Sandbox Code Playgroud)

如果我们只想要一个事物名称列表:

In [17]: [x.name for x in Path('/etc').iterdir()]
Out[17]:
['emond.d',
 'ntp-restrict.conf',
 'periodic',
Run Code Online (Sandbox Code Playgroud)

如果你只想要目录:

In [18]: [x.name for x in Path('/etc').iterdir() if x.is_dir()]
Out[18]:
['emond.d',
 'periodic',
 'mach_init.d',
Run Code Online (Sandbox Code Playgroud)

如果您想要该树中所有conf文件的名称:

In [20]: [x.name for x in Path('/etc').glob('**/*.conf')]
Out[20]:
['ntp-restrict.conf',
 'dnsextd.conf',
 'syslog.conf',
Run Code Online (Sandbox Code Playgroud)

如果您想要树中 >= 1K 的 conf 文件列表:

In [23]: [x.name for x in Path('/etc').glob('**/*.conf') if x.stat().st_size > 1024]
Out[23]:
['dnsextd.conf',
 'pf.conf',
 'autofs.conf',
Run Code Online (Sandbox Code Playgroud)

解析相对路径变得很容易:

In [32]: Path('../Operational Metrics.md').resolve()
Out[32]: PosixPath('/Users/starver/code/xxxx/Operational Metrics.md')
Run Code Online (Sandbox Code Playgroud)

使用路径导航非常清晰(尽管出乎意料):

In [10]: p = Path('.')

In [11]: core = p / 'web' / 'core'

In [13]: [x for x in core.iterdir() if x.is_file()]
Out[13]:
[PosixPath('web/core/metrics.py'),
 PosixPath('web/core/services.py'),
 PosixPath('web/core/querysets.py'),
Run Code Online (Sandbox Code Playgroud)


Arn*_*ira 5

递归实现

import os

def scan_dir(dir):
    for name in os.listdir(dir):
        path = os.path.join(dir, name)
        if os.path.isfile(path):
            print path
        else:
            scan_dir(path)
Run Code Online (Sandbox Code Playgroud)


Kha*_*ino 5

这是另一种选择。

os.scandir(path='.')
Run Code Online (Sandbox Code Playgroud)

它返回与路径给定的目录中的条目(以及文件属性信息)相对应的 os.DirEntry 对象的迭代器。

例子:

with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.'):
            print(entry.name)
Run Code Online (Sandbox Code Playgroud)

使用 scandir() 而不是 listdir() 可以显着提高还需要文件类型或文件属性信息的代码的性能,因为如果操作系统在扫描目录时提供此信息,则 os.DirEntry 对象会公开此信息。所有 os.DirEntry 方法都可以执行系统调用,但 is_dir() 和 is_file() 通常只需要符号链接的系统调用;os.DirEntry.stat() 在 Unix 上总是需要系统调用,但在 Windows 上只需要符号链接。

Python 文档