繁体   English   中英

Python 中是否有一种方法可以在不使用 os.walk、glob 或 fnmatch 的情况下递归搜索目录、子目录和文件?

[英]Is there a way in Python to search directories, subdirectories and files recursively without using os.walk, glob, or fnmatch?

我知道使用这些模块会让生活变得更轻松,但是当我学习 Python 时,我希望能够巩固基础,然后走捷径。 这样,当遇到更大的问题时,我可以分析和解决它。

我希望能够返回 1 个目录中的文件夹和文件总数,例如目录 F:\\

我想出了:

import os

def fcount(path):
  count = 0
  for f in os.listdir(path):
    file = os.path.join(path, f)
    if os.path.isdir(file):
      file_count = fcount(file)
      count += file_count + 1

  for f in os.listdir(path):
    if os.path.isfile(os.path.join(path, f)):
      count += 1
  return count

path = 'F:\\'
print(fcount(path))

这是最终答案。 这为您提供指定目录中子目录和文件的总数。

如果不使用os.walk或使用相同内容的内容,则无法(递归地)获取目录下所有文件的数量。

此信息需要此工作,您不能以其他方式完成。 显然,还有其他图书馆在做类似的工作,但有一些变化,但重点是这主要是同一件事。

这是与 os.walk 一样的代码。 这是手动递归。

import os

def fcount(path):
    count = 0
    for f in os.listdir(path):
        file = os.path.join(path, f)
        if os.path.isdir(file):
            file_count = fcount(file)
            count += file_count + 1

    for f in os.listdir(path):
        if os.path.isfile(os.path.join(path, f)):
        count += 1
    return count

path = 'F:\\'
print(fcount(path))

注意:最初在 OP 中,没有第二个循环。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM