简体   繁体   中英

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. 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:\\

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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