简体   繁体   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?

I know that using these modules makes life a lot easier but as I learn Python, I want to be able to solidify the foundation and then go onto the shortcuts.我知道使用这些模块会让生活变得更轻松,但是当我学习 Python 时,我希望能够巩固基础,然后走捷径。 That way, when presented with the bigger issue, I can analyze and solve it.这样,当遇到更大的问题时,我可以分析和解决它。

I want to be able to return the number of total folders and files in 1 directory such as directory F:\\我希望能够返回 1 个目录中的文件夹和文件总数,例如目录 F:\\

I have come up with:我想出了:

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))

This is the final answer.这是最终答案。 This gives you the total number of subdirectories and files within the specified directory.这为您提供指定目录中子目录和文件的总数。

You cannot get the number of all files under a directory (recursively) without using os.walk or something that uses the same thing.如果不使用os.walk或使用相同内容的内容,则无法(递归地)获取目录下所有文件的数量。

This information requires this job and you cannot do it another way.此信息需要此工作,您不能以其他方式完成。 Obviously that there are other libraries that are doing a similar job with some variations but the point is that's the mainly the same thing.显然,还有其他图书馆在做类似的工作,但有一些变化,但重点是这主要是同一件事。

This is the code to do just as os.walk would do.这是与 os.walk 一样的代码。 It's manual recursion.这是手动递归。

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))

Note: Initially in OP, there was no second loop.注意:最初在 OP 中,没有第二个循环。

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

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