gpt4 book ai didi

相当于 "find -type f"的 Python

转载 作者:太空宇宙 更新时间:2023-11-04 09:03:40 24 4
gpt4 key购买 nike

在 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 中)如何在指定路径下递归地获取所有 文件(不包括目录)的列表?我还希望路径的标题能够反射(reflect)输入的路径。例如,如果我(在/etc 中)运行了 find 。 -type f 我会得到如下列表:

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

区别在于 /etc/... 与 ./...

最佳答案

您可以 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')

获取你想要的相对路径。

关于相当于 "find -type f"的 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23003707/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com