2015-07-02 124 views
0

我正在試圖獲取以特定擴展名(哪個用戶將通過)與路徑結尾的所有文件的計數。我們也有子文件夾,因此搜索必須遞歸。 下面是我正在嘗試,但它是拋出錯誤。請建議差距在哪裏。 如果刪除if file.endswith(extension):線然後它給出的所有文件的計數值(它包括與所有擴展名的文件)具有特定擴展名的文件的遞歸搜索

import os, sys 

def fileCount(path, extension): 
    count = 0 
    for root, dirs, file in os.walk(path): 
     if file.endswith(extension): 
      count += len(file) 
    return count 

print fileCount('/home/export/JobDefinition', '.car') 

下面是輸出:通過文件小號

$ python test.py 
Traceback (most recent call last): 
    File "test.py", line 11, in <module> 
    print fileCount('/home/export/JobDefinition', '.car') 
    File "test.py", line 6, in fileCount 
    if file.endswith(extension): 
AttributeError: 'list' object has no attribute 'endswith' 

回答

2

你想的和過濾的所有文件後:

def fileCount(path, extension): 
    count = 0 
    for root, dirs, files in os.walk(path): 
     count += sum(f.endswith(extension) for f in files) 
    return count 

files返回文件的列表,以便sum(f.endswith(extension) for f in files)會給你指定的擴展名結尾的所有文件的計數。

或者只是返回所有的總和:

def fileCount(path, extension): 
    return sum(f.endswith(extension) for root, dirs, files in os.walk(path) for f in files) 
+1

優秀的答案,並一如既往非常優雅...你也可以使用'len'(但我喜歡總和解決方案:P) –

+0

我把它歸結爲一行;) – heinst

+1

@JoranBeasley,謝謝,yep len會工作正常,但gen exp避免了需要建立一個列表,除非列表很大,否則可能沒有真正的區別。 –

1

os.walk()用於迭代。

您必須遍歷文件S,它們以list的形式返回。

def fileCount(path, extension): 
    count = 0 
    for root, dirs, files in os.walk(path): 
     for file in files: 
      if file.endswith(extension): 
       count += 1 
    return count 
+0

我已經嘗試這樣做,它給了我3333作爲計數是辦法不多。我想這是給我所有文件的所有字符數。 – ankitpandey

+0

@ankitpandey我編輯了我的答案:也許你應該使用'count + = 1'來代替,這似乎是合乎邏輯的。 – Delgan

1

os.walk()返回一個元組,如 - (dirpath, dirnames, filenames)。其中filenames是目錄中所有文件的列表,其a list

您需要遍歷文件,而不是使用file.endswith

示例 -

import os, sys 

def fileCount(path, extension): 
    count = 0 
    for root, dirs, files in os.walk(path): 
     for file in files: 
      if file.endswith(extension): 
       count += 1 
    return count 

print fileCount('/home/export/JobDefinition', '.car') 
+0

我已經試過這個,它給了我3333作爲計數,這是很多的方式。我想這是給我所有文件的所有字符數。 – ankitpandey

+0

編輯答案後,我們需要添加'1'來計算每個帶擴展名的文件,而不是'len(files)'。 –

0

os.walk第三返回值是文件名的列表。

1

這裏是一個內襯替代:

import os 

def fileCount(path, extension): 
    return sum([1 for root, dirs, files in os.walk(path) for file in files if file.endswith(extension)]) 

print fileCount('/home/export/JobDefinition', '.car') 
+1

我不認爲這是相當你想要的.. 。我懷疑你會得到比你想象的更大的值 –

+0

@JoranBeasley我對它的完整代碼進行了測試,並返回相同的數字 – heinst

+0

是的,那是因爲原始代碼也是錯誤的......這是文件名字符串長度的總和匹配搜索(不匹配的數量) –

相關問題