python os.walk 到某个级别

标签 python directory subdirectory python-os

<分区>

我想构建一个程序,使用一些基本代码来读取文件夹并告诉我文件夹中有多少文件。 这是我目前的做法:

import os

folders = ['Y:\\path1', 'Y:\\path2', 'Y:\\path3']
for stuff in folders:
    for root, dirs, files in os.walk(stuff, topdown=True):
        print("there are", len(files), "files in", root)

在“主”文件夹中有多个文件夹之前,此方法效果很好,因为由于文件夹/文件管理不善,它可能会返回一长串无用的文件。所以我想最多只去二级。示例:

Main Folder
---file_i_want
---file_i_want
---Sub_Folder
------file_i_want <--*
------file_i want <--*
------Sub_Folder_2
---------file_i_dont_want
---------file_i_dont_want

我知道如何使用 breakdel dirs[:]this post 进入第一层和 also this post .

import os
import pandas as pd

folders = ['Y:\\path1', 'Y:\\path2', 'Y:\\path3']
for stuff in folders:
    for root, dirs, files in os.walk(stuff, topdown=True):
        print("there are", len(files), "files in", root)
        del dirs[:] # or a break here. does the same thing.

但无论我如何搜索,我都找不到如何深入两层的方法。我可能只是不理解上面的其他帖子之类的?我在想类似 del dirs[:2] 但无济于事。有人可以指导我或向我解释如何完成此操作吗?

最佳答案

你可以这样做:

depth = 2

# [1] abspath() already acts as normpath() to remove trailing os.sep
#, and we need ensures trailing os.sep not exists to make slicing accurate. 
# [2] abspath() also make /../ and ////, "." get resolved even though os.walk can returns it literally.
# [3] expanduser() expands ~
# [4] expandvars() expands $HOME
# WARN: Don't use [3] expanduser and [4] expandvars if stuff contains arbitrary string out of your control.
#stuff = os.path.expanduser(os.path.expandvars(stuff)) # if trusted source
stuff = os.path.abspath(stuff)

for root,dirs,files in os.walk(stuff):
    if root[len(stuff):].count(os.sep) < depth:
        for f in files:
            print(os.path.join(root,f))

关键是:if root[len(stuff):].count(os.sep) < depth

它删除了 stuff来自 root , 所以结果是相对于 stuff .只需计算文件分隔符的数量即可。

深度就像find在 Linux 中找到的命令,即 -maxdepth 0表示什么都不做,-maxdepth 1仅扫描第一级文件,-maxdepth 2扫描文件包含子目录。

当然,它仍然会扫描完整的文件结构,但除非它非常深,否则它会起作用。

另一个解决方案是只使用 os.listdir递归地(通过目录检查)最大递归级别,但如果你不需要它,那就有点棘手了。由于这并不难,这里是一种实现方式:

def scanrec(root):
    rval = []

    def do_scan(start_dir,output,depth=0):
        for f in os.listdir(start_dir):
            ff = os.path.join(start_dir,f)
            if os.path.isdir(ff):
                if depth<2:
                    do_scan(ff,output,depth+1)
            else:
                output.append(ff)

    do_scan(root,rval,0)
    return rval

print(scanrec(stuff))  # prints the list of files not below 2 deep

备注:os.listdiros.path.isfile执行 2 stat调用不是最优的。在 Python 3.5 中,使用 os.scandir可以避免重复调用。

关于python os.walk 到某个级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42720627/

相关文章:

python-在多个文件上运行脚本

python - 将数据框列中的元组列表拆分为数据框的列

bash - 如何确定两个目录不是彼此的子目录(BASH)

qt - qmake 子目录模板同时运行所有应用程序

python - 在 pyqt 中使用复选框

python - 多标签分类交叉验证错误

Android:将文件从一个目录复制到另一个目录

file - 如何将文件夹中的文件名提取为文本?

bash - 使用 bash 删除目录中未链接的所有文件夹

joomla - Joomla! 的单个实例、子目录和多个域