总计似乎是错的

gee*_*ers 0 python

我有以下代码,简单我知道(请随时建议改进)

看来用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))
Run Code Online (Sandbox Code Playgroud)

提前致谢

Sve*_*ach 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'))
Run Code Online (Sandbox Code Playgroud)