相当于python 3中的find coreutil命令,用于递归返回目录结构中的所有文件和文件夹? [英] equivalent to the find coreutil command in python 3 for recursively returning all files and folders in a directory structure?

查看:24
本文介绍了相当于python 3中的find coreutil命令,用于递归返回目录结构中的所有文件和文件夹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 python (3) 中递归返回目录结构中的所有文件和文件夹的最佳替代方法是什么?

What is best alternative to find in python (3) for recursively returning all files and folders in a directory structure?

我想要类似的东西:

find ~/x/y/ > ~/matches.txt

我从另一个问题中重写了一个提示,得到了一些类似的东西,但有一些问题:>

I rewrote a tip from another question and got something that kind of works, but it has some problems:

matches = glob.glob("/Users/x/y/*/*)

如果~/x/y/"中有任何可能发生的文件,这将不起作用,我也不确定这是一种稳健或惯用的方法.

This will not work if there are any files in "~/x/y/" which could happen I'm also not sure it's a robust or idiomatic way to do this.

那么在 Python 中复制上述 find 命令的最佳方法是什么?

So what's the best way to copy the above find command in Python?

推荐答案

您可以使用 os.walk:

You can use os.walk:

获取目录、文件名列表:

To get directory, file name list:

import os

matches = []
for dirpath, dirnames, filenames in os.walk(os.path.expanduser('~/x/y')):
    matches.extend(os.path.join(dirpath, x) for x in dirnames + filenames)

将文件列表写入文本文件:

To write the file list to text file:

import os

with open(os.path.expanduser('~/matches.txt'), 'w') as f:
    for dirpath, dirnames, filenames in os.walk(os.path.expanduser('~/x/y')):
        for x in dirnames + filenames:
            f.write('{}\n'.format(os.path.join(dirpath, x)))

os.path.expanduser 用于将 ~ 替换为主目录路径.

替代使用 pathlib.Path.rglob 自 Python 3.4 起可用:

Alternative using pathlib.Path.rglob which available since Python 3.4:

import os
import pathlib

matches = list(map(str, pathlib.Path(os.path.expanduser('~/x/y')).rglob('*')))

<小时>

import os
import pathlib

with open(os.path.expanduser('~/matches.txt'), 'w') as f:
    for path in pathlib.Path(os.path.expanduser('~/x/y')).rglob('*'):
        f.write('{}\n'.format(path))

这篇关于相当于python 3中的find coreutil命令,用于递归返回目录结构中的所有文件和文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆