簡體   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