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


当前回答

虽然os.listdir()用于生成文件和目录名称的列表很好,但一旦有了这些名称,通常您还想做更多的事情——在Python3中,pathlib使这些其他杂事变得简单。让我们看一看,看看你是否和我一样喜欢它。

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

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

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

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

如果你只想要dirs:

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

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

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

如果你想在树>= 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',

解析相对路径变得简单:

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

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

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'),

其他回答

对于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)])

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

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

将返回如下内容:

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

请在这里查看文档。

供参考添加扩展或ext文件的过滤器 进口操作系统

path = '.'
for dirname, dirnames, filenames in os.walk(path):
    # print path to all filenames with extension py.
    for filename in filenames:
        fname_path = os.path.join(dirname, filename)
        fext = os.path.splitext(fname_path)[1]
        if fext == '.py':
            print fname_path
        else:
            continue

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

Python 2.7:

import os
os.listdir('.')

Python 3. x:

import os
os.listdir()

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

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')