2014-10-30 24 views
1

子文件夾中的文件的打印張數我的文件夾結構如下
文件夾A
文件夾B1
文件夾B2
....
文件夾BN計數和使用Python

我怎樣才能算每個文件夾中的文件數量(文件夾B1 - 文件夾Bn),檢查文件數量是否大於給定限制,並在屏幕上打印文件夾名稱和文件數量?

像這樣:
文件夾與文件太多:
文件夾B3 101
文件夾B7 256

這是我到目前爲止已經試過。它通過我的每個文件夾B1中的每個子文件夾等我只需要在一個級別的文件計數。

import os, sys ,csv 
path = '/Folder A/' 

outwriter = csv.writer(open("numFiles.csv", 'w') 

dir_count = [] 

for root, dirs, files in os.walk(path): 
    for d in dirs: 
     a = str(d) 
     count = 0 
     for fi in files: 
      count += 1 
     y = (a, count) 
     dir_count.append(y) 

    for i in dir_count: 
     outwriter.writerow(i) 

然後我只是打印numFiles.csv。我不太想如何去做。 在此先感謝!

+0

試試這個庫https://docs.python.org /2/library/os.html – 2014-10-30 11:27:17

+0

我已更新我的帖子以顯示迄今爲止我嘗試過的內容,Alex Thornton。我是Python新手,所以我非常需要幫助。 – selveste 2014-10-30 11:39:39

+0

他們都在一個目錄? – 2014-10-30 11:42:43

回答

4

由於都包含在一個文件夾中,你只需要搜索該目錄:

import os 
path = '/Folder A/' 
mn = 20 
folders = ([name for name in os.listdir(path) 
      if os.path.isdir(os.path.join(path, name)) and name.startswith("B")]) # get all directories 
for folder in folders: 
    contents = os.listdir(os.path.join(path,folder)) # get list of contents 
    if len(contents) > mn: # if greater than the limit, print folder and number of contents 
     print(folder,len(contents) 
+0

這就像一個魅力,Padraic!非常感謝你! – selveste 2014-10-30 12:18:52

+0

沒有問題,不客氣 – 2014-10-30 19:07:51

-1

os.walk(path)爲您提供了三元組的目錄,即(directory,subdirectory,files)。 目錄 - >當前目錄中的所有目錄列表,當前目錄中的子目錄列表,當前目錄中的文件列表。
所以你可以代碼喜歡這樣的:

import os 
for dir,subdir,files in os.walk(path): 
    if len(files) > your_limit: 
     print dir + " has crossed limit, " + "total files: " + len(files) 
     for x in files: 
      print x 

,如果你想走路只有一個級別,你需要這樣的代碼:

for x in os.listdir(path): 
    if os.path.isdir(x): 
     count = len([ y for y in os.listdir(x) if os.path.isfile(os.path.join(x,y)) ]) 
     if count > your_limit: 
      print x + " has crossed limit: ", +count 
+0

這也行得通,但Padraics的代碼輸出更好。不管怎麼說,還是要謝謝你! – selveste 2014-10-30 12:29:01