Python相当于"find -type f"

Dan*_*lTA 1 python recursion search file python-3.x

Python 3中bash命令的等价物是find -type f什么?

find /etc/ -type f
Run Code Online (Sandbox Code Playgroud)

会生成一个看起来像这样的列表:

/etc/rsyslog.conf
/etc/request-key.d/cifs.idmap.conf
/etc/request-key.d/id_resolver.conf
/etc/issue
/etc/maven/maven2-depmap.xml
/etc/gtkmathview/gtkmathview.conf.xml
/etc/fstab
/etc/machine-id
/etc/rpmlint/mingw-rpmlint.config
/etc/rpmlint/config
/etc/cupshelpers/preferreddrivers.xml
/etc/pulse/system.pa
/etc/pulse/daemon.conf
/etc/brltty.conf
/etc/numad.conf
...
Run Code Online (Sandbox Code Playgroud)

我将如何(在Python 3中)在指定路径下递归获取所有文件(不包括目录)的列表?我还希望路径的标题能够镜像输入的路径.例如,如果我(在/ etc中)运行,find . -type f我会得到一个列表,如:

./rsyslog.conf
./request-key.d/cifs.idmap.conf
...
Run Code Online (Sandbox Code Playgroud)

不同的是/ etc / ... vs./ ...

mgi*_*son 5

您可以os.walk然后查看检查"类型"的每个文件os.path.isfile.这应该让你非常接近......

import os
import os.path

for root, dirs, files in os.walk('/path/to/directory'):
    for f in files:
        fname = os.path.join(root, f)
        if os.path.isfile(fname):
            print fname  # or do something else with it...
Run Code Online (Sandbox Code Playgroud)

我不知道你在哪里与打算/etc./你的问题的东西,但我怀疑,如果这是不是你想要的,那么你只需要像做

os.path.relpath(fname, '/path/to/directory')
Run Code Online (Sandbox Code Playgroud)

获得你想要的相对路径.