-1

Is there a simple way to count the total number of pdf files in a folder that contains a number of other folders among which some contain multiple level subfolders and others just pdf files?

This answer provides a very good solution to count number of files in each folder on the first subfolder level but not further down to individual pdf files.

1
  • 1
    pls show your code. Commented Jun 23, 2021 at 2:26

2 Answers 2

3

Provided your pdfs end in the expected file extension, the solution is trivial:

import os
my_folder = "./" # your path here
count = 0
for root, dirs, files in os.walk(my_folder):
    count += len([fn for fn in files if fn.endswith(".pdf")])
print(count)

It is a separate question if you want to determine the filetype by the contents directly; that is a harder problem.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi anon01 thanks for the succinct answer! Could you please add some comments to elaborate this method?
no need, python has that built in. Try help(os.walk) and scroll to the example at the bottom. The code should look familiar :D
0

Is this what you want?

import os
count=0
def new_folder(path,arrs):
    global count
    
    for arr in arrs:
        if os.path.isdir(path+"\\"+arr): #=== Joins the path with the name and check if it is a folder
            try:
                a1=os.listdir(path+"\\"+arr)
                new_folder(path+"\\"+arr,a1) #=== Pass that as a function and iterate over it.

            except PermissionError: #=== Permission denied
                pass
        else:
            if arr.endswith(".pdf"): #=== If it ends with a .pdf extension 
                print(path+"\\"+arr) #=== Print file path
                count+=1 #=== Add 1 to count
    return count

path="C:\\Users\\91996"
arrss=os.listdir(path) #== List all files and directories 
print("PDF Files Found: ",new_folder(path,arrss))

2 Comments

Hi Sujay, yes, thanks for the awesome answer! Do you mind adding some brief comments for learning purpose?
why use a global counter?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.