Python中等效于"find -type f"的命令

1 投票
2 回答
1303 浏览
提问于 2025-04-18 02:18

在Python 3中,怎么实现和bash命令 find -type f 一样的功能呢?

find /etc/ -type f

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

/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
...

我想知道在Python 3中,如何获取一个指定路径下所有的文件(不包括文件夹)的列表,并且这个列表的路径要和我输入的路径一致。比如说,如果我在 /etc 目录下运行 find . -type f,我会得到一个像这样的列表:

./rsyslog.conf
./request-key.d/cifs.idmap.conf
...

不同之处在于 /etc/... 和 ./...

2 个回答

0

你可以在Python中使用subprocess来执行系统命令:

import subprocess
output=subprocess.check_output(['find /etc/ -type f'])
print output

或者使用commands模块:

import commands
output=commands.getstatusoutput('find /etc/ -type f')
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...

我不太确定你提到的 /etc./ 是什么意思,但我猜如果这不是你想要的结果,那你可能需要做一些类似于

os.path.relpath(fname, '/path/to/directory')

的操作,来获取你想要的相对路径。

撰写回答