2016-05-29 1 views
0

os.walk()、globまたはfnmatchを使用せず意図的なこのプログラムを作成しました。ディレクトリとその指定されたディレクトリ内のすべてのサブディレクトリとファイルを調べ、そこにいくつのファイル+フォルダがあるかを返します。私が得た再帰コードを使用して、2つの値のセット(合計ファイル、フォルダ)を返したい

import os 

def fcount(path): 
    count = 0 

    '''Folders''' 
    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 

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

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

の出力例は、Fは700個のファイルとフォルダの合計のために私に700を与えたディレクトリでした。

ここで私がやりたいことは、もちろんこのコードを使って、fcount('F:\\')を呼び出して(total files, folders)を返すことです。

出力の例は、(700, 50)です。 700files + foldersであり、50はちょうどfoldersです。

どうすればよいか分かりません。

+1

はい、タプルを使用してください。どうしたの? –

+0

@KarolyHorvathこのコードセットでタプルを実装する方法がわかりません。 – adhamncheese

答えて

2

2つのカウントを維持し、タプルとしてそれらを返す:

total_count = dir_count = 0, 0 
# .. increment either as needed 
return total_count, dir_count 

あなただけ一度os.listdir()上でループする必要があります。何かがファイルまたはディレクトリである場合、あなたはまだそれだけで一つのループで分化検出:最終print()はカウントしてタプルを印刷し、その後

def fcount(path): 
    total_count = dir_count = 0 

    for f in os.listdir(path): 
     file = os.path.join(path, f) 
     if os.path.isdir(file): 
      recursive_total_count, recursive_dir_count = fcount(file) 
      # count this directory in the total and the directory count too 
      total_count += 1 + recursive_total_count 
      dir_count += 1 + recursive_dir_count 
     elif if os.path.isfile(file): 
      total_count += 1 
    return file_count, total_count 

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

total_count, dir_count = fcount(path) 
print('Total:', total_count) 
print('Directories:', dir_count) 
+0

私は今それを見る。私は各ループにカウントを追加していました。私がそれをしていたので、それぞれのループに対して別々の答えを得ることは不可能でした。さて、私はこれを理解するだけです。ありがとうございました! – adhamncheese