2012-02-27 100 views
0

我有以下的代碼,簡單的我知道(請隨時提出改進建議)總計似乎是錯誤

這似乎與shell腳本的功能,總好像是錯的,我算22,但它是報告42,代碼有問題嗎?

import os 

myPath = os.getenv("scripts") 
pyCounter = 0 
sqlCounter = 0 
shCounter = 0 

def python_scripts(): 
    global pyCounter 
    for root, dirs, files in os.walk(myPath):  
    for file in files:    
     if file.endswith('.py'):    
     pyCounter += 1 

def sql_scripts(): 
    global sqlCounter 
    for root, dirs, files in os.walk(myPath):  
    for file in files:    
     if file.endswith('.sql'):    
     sqlCounter += 1 

def sh_scripts(): 
    global shCounter 
    shell_ext = ['ksh','sh','bash'] 
    for shell in shell_ext: 
    for root, dirs, files in os.walk(myPath):  
     for file in files:    
     if file.endswith(shell): 
      shCounter += 1 

python_scripts() 
sql_scripts() 
sh_scripts() 

print ("Python : " + str(pyCounter)) 
print ("SQL : " + str(sqlCounter)) 
print ("Shell : " + str(shCounter)) 

在此先感謝

+0

請用四個空格和* no *製表符縮進您的可能。 – 2012-02-27 12:05:03

+0

'sh_scripts'中的縮進錯誤:我無法分辨出最後一行屬於哪個塊,Python也無法做到這一點。 – 2012-02-27 12:06:47

+2

另外,如果你的問題是'sh_scripts',爲什麼你在你的代碼中包含所有其他函數?不要讓我們讀任何超出我們需要的東西。 – 2012-02-27 12:08:25

回答

9

你計數了,因爲在bashksh結尾的文件名也sh結束。你應該包括一個.以確保這是真正的擴展。你也可以傳遞一個字符串元組到str.endswith(),避免其中一個循環。

這是您的代碼清理了一下。這三個函數基本上是做同樣的事情,只是擴展名不同,所以你應該寫一個接受參數的函數。而不是使用全局變量作爲計數器,只需返回以下值:

def count_files(path, extensions): 
    counter = 0 
    for root, dirs, files in os.walk(path): 
     for file in files: 
      counter += file.endswith(extensions) 
    return counter 

path = os.getenv("scripts") 
print count_files(path, '.py') 
print count_files(path, '.sql') 
print count_files(path, ('.ksh', '.sh', '.bash')) 
+0

這就是它,它已經解決了它。非常感謝你。我雖然會有更簡單的方法來編寫代碼,但還有很多東西需要學習。再次感謝 – geekcomputers 2012-02-27 12:43:20

2

使用fnmatch.filter對於這種事情,例如:

import fnmatch 
import os 

py_files = [] 
for root, dirnames, filenames in os.walk(myPath): 
    for filename in fnmatch.filter(filenames, '*.py'): 
     py_files.append(os.path.join(root, filename)) 

pyCounter = len(py_files) 
1

您並不需要多次走過目錄樹。

在走路時,您可以使用collections.Counter()跟蹤所看到的所有分機。

例子:

import os 
from collections import Counter 
path = '.' 

c = Counter(os.path.splitext(f)[1] for _, _, files in os.walk(path) for f in files) 

# now you'll just need to sum or extract the counts that you want 
sh_ext = ('.ksh', '.sh', '.bash') 
sh_scripts = sum(c[ext] for ext in sh_ext) 
py_scripts = c['.py'] 

採取延長WIM建議使用os.path.splitext(),這是一個很好的建議。看看商務部:

os.path.splitext(path)

斯普利特路徑路徑爲一對(root, ext)這樣root + ext == path分機爲空或有一個週期開始,幷包含在最多一個時期。基準名稱上的主要時段將被忽略; splitext('.cshrc')返回('.cshrc', '')

+0

+1不錯的解決方案。但我寧願使用'os.path.splitext'來獲得擴展名。 – wim 2012-02-27 23:08:58

+0

@wim:非常好的建議 - 我已經更新了答案。 – 2012-02-28 08:56:34