Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from sys import argv
- import os
- import file_class
- def main():
- if len(argv) <= 1 or os.path.exists(argv[1]) == False:
- usage()
- # If the path exists and is specified, variables are initialized and packed into a list for easier passing to/from traversal function
- path = argv[1]
- userPath = os.path.normpath(path)
- pyFilesList = [ ]
- initialFiles = 0
- print("\n"+ "Original Path is Python file: "+ str(pyCheck(path)) + "\n")
- finalData = dirTraversal(userPath, pyFilesList, initialFiles)
- # Unpacks return tuple to separate Python file instance list from total count of files
- finalPyList = finalData[0]
- finalTotalFiles = finalData[1]
- finalPyCount = 0
- finalLineCount = 0
- # Computes and outputs total counts and average number of lines
- for instance in finalPyList:
- finalPyCount += 1
- finalLineCount += instance.getLines()
- print("Final Total File Count: "+ str(finalTotalFiles))
- print("Final Python File Count: "+ str(finalPyCount))
- print("Final Python File Line Count: "+ str(finalLineCount))
- print("Average Number of Lines per Python file: " + str(finalLineCount / finalPyCount))
- def dirTraversal(anyPath, pyFilesList, totalFiles):
- if os.path.isfile(anyPath):
- # Terminating condition for Python files
- if pyCheck(anyPath) == True:
- newPyFile = file_class.File()
- newPyFile.setPath(anyPath)
- newPyFile.setName(os.path.basename(anyPath))
- newPyFile.setLines(countLines(anyPath))
- pyFilesList.append(newPyFile)
- totalFiles += 1
- return pyFilesList, totalFiles
- # Terminating condition for non-Python files
- else:
- totalFiles += 1
- return pyFilesList, totalFiles
- # Handles non-file cases
- else:
- files = os.listdir(anyPath)
- origPath = anyPath
- for x in range(len(files)):
- newPath = str(origPath) + "/" + str(files[x])
- subfolderData = dirTraversal(newPath, pyFilesList, totalFiles)
- totalFiles = subfolderData[1]
- return pyFilesList, totalFiles
- # Checks to see if the given path is a Python file
- def pyCheck(path):
- if path.endswith(".py"):
- return True
- else:
- return False
- # Counts the number of lines in a given Python file
- def countLines(path):
- lineCount = 0
- countFile = open(path, "r")
- for line in countFile:
- lineCount += 1
- countFile.close()
- return lineCount
- def usage():
- print("Usage: python3 recursive_dir_traversal.py 'path/to/file/written/like/this/quotes/included' ")
- exit(0)
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement