'How can I find the number of files within a directory?

I was wondering how I can find the number of files I have in a certain folder. For example in this file containing about 1000 excel files:

from pathlib import Path
fileDir = Path("C:/Users/Jonas/Desktop/Test")

Thanks.



Solution 1:[1]

Here's a little function I put together that will list all the files in a given folder. You can then use the length of the list to see how many there are, or loop though the list if you want to do anything with them:

import os

def list_files(folder, extensions=None):
    file_list = []
    all_files = os.listdir(folder)
    for name in all_files:
        if extensions is not None:
            for ext in extensions:
                if name.endswith(ext):
                    file_list.append(f'{folder}{os.sep}{name}')
        else:
            file_list.append(f'{folder}{os.sep}{name}')
    return file_list

if __name__ == '__main__':
    all_files = list_files('C:/Users/Jonas/Desktop/Test')
    print('total files: ')
    print(len(all_files))

    all_excel_files = list_files('C:/Users/Jonas/Desktop/Test', ['xlsx', 'xls', 'xlsm'])
    print('excel files:')
    print(len(all_excel_files))

Solution 2:[2]

You can use this:

import os
import glob
files = 0
folder_path = 'your path'
    for filename in glob.glob(os.path.join(folder_path, '*.xls')): # .xls for example
        files += 1

Solution 3:[3]

If you need the number of all files, you could do something like this:

from pathlib import Path
fileDir = Path("C:/Users/Jonas/Desktop/Test")

print(len[f for f in fileDir.iterdir()])

If you need to filter on the name, you can add a condition on f.name or use fileDir.glob() or fileDir.rglob(), like the others suggested. E.g,

from pathlib import Path
fileDir = Path("C:/Users/Jonas/Desktop/Test")

print(len[f for f in fileDir.iterdir() if len(f.name) < 10])

Solution 4:[4]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 PangolinPaws
Solution 2
Solution 3 Arseny
Solution 4 JieGH