Return number of files in directory and subdirectory

前端 未结 3 1853
抹茶落季
抹茶落季 2020-12-30 19:25

Trying to create a function that returns the # of files found a directory and its subdirectories. Just need help getting started

相关标签:
3条回答
  • 2020-12-30 19:48

    Use os.walk. It will do the recursion for you. See http://www.pythonforbeginners.com/code-snippets-source-code/python-os-walk/ for an example.

    total = 0
    for root, dirs, files in os.walk(folder):
        total += len(files)
    
    0 讨论(0)
  • 2020-12-30 20:07

    Just add an elif statement that takes care of the directories:

    def fileCount(folder):
        "count the number of files in a directory"
    
        count = 0
    
        for filename in os.listdir(folder):
            path = os.path.join(folder, filename)
    
            if os.path.isfile(path):
                count += 1
            elif os.path.isfolder(path):
                count += fileCount(path)
    
        return count
    
    0 讨论(0)
  • 2020-12-30 20:10

    One - liner

    import os
    cpt = sum([len(files) for r, d, files in os.walk("G:\CS\PYTHONPROJECTS")])
    
    0 讨论(0)
提交回复
热议问题