2012-02-27 145 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