I have the following code, simple I know (please feel free to recommend improvements)
It seems with the shell scripts function, the total seems to be wrong, I count 22 but it is reporting 42, is there a problem with the code.
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))
Thanks in advance
Your counts are off because a file name ending in
bashorkshalso ends insh. You should include a.to make sure this is really the extension. You can also pass a tuple of strings tostr.endswith(), avoiding one of the loops.Here’s your code cleaned up a bit. The three functions are basically doing the same thing, just with different extensions, so you should write a single function accepting a parameter. Instead of using global variables for the counters, simply return the values: