I am trying to count the number of python files and non-python files in a path recursively.
import os
def main():
    #path = input('Enter an existing path to a file or directory: ')
    path ='/Users/ziyuanhan/PycharmProjects/lab6/'
    print(count_file(path, counter={'py':0, 'non_py':0}))
def count_file(path,counter):
    if os.path.isfile(path):
        if path.endswith('.py') :
            counter['py']+=1
            return path, counter
        else:
            counter['non_py']+=1
            return path, counter
    elif os.path.isdir(path):
        for files in os.listdir(path):
            print(files)
            path = os.path.abspath(files)
            print(path)
            count_file(path, counter)
        return path, counter
main()
The few problems I have is
- I had trouble in keeping multiple counters in one recursion function.
- Also the return I want is a dictionary format, but I can only do it this way because I have to return it with path.
- I use print(files)to check if the function is working alright, but it shows a lot more files(the top 7 files) I never seen in my folder, why is this happening?
When print(files)
/Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 
/Users/ziyuanhan/PycharmProjects/lab7/recursive_dir_traversal.py
.DS_Store
/Users/ziyuanhan/PycharmProjects/lab7/.DS_Store
.idea
/Users/ziyuanhan/PycharmProjects/lab7/.idea
lab7.iml
/Users/ziyuanhan/PycharmProjects/lab7/lab7.iml
misc.xml
/Users/ziyuanhan/PycharmProjects/lab7/misc.xml
modules.xml
/Users/ziyuanhan/PycharmProjects/lab7/modules.xml
workspace.xml
/Users/ziyuanhan/PycharmProjects/lab7/workspace.xml
km_mi_table.py
/Users/ziyuanhan/PycharmProjects/lab7/km_mi_table.py
km_to_miles.py
/Users/ziyuanhan/PycharmProjects/lab7/km_to_miles.py
wordfrequency.py
/Users/ziyuanhan/PycharmProjects/lab7/wordfrequency.py
('/Users/ziyuanhan/PycharmProjects/lab7/wordfrequency.py', {'non_py': 0, 'py': 0})
BTW we have to use recursive function, it is mandatory as the Prof requested.
 
     
     
     
    