2

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.

  • Probably a duplicate. This may help you: https://stackoverflow.com/questions/2632205/how-to-count-the-number-of-files-in-a-directory-using-python – T.Harms Feb 01 '22 at 10:36
  • Also, see https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory – Arseny Feb 01 '22 at 10:48

5 Answers5

1

You could use .glob() or .rglob():

from pathlib import Path
fileDir = Path("C:/Users/Jonas/Desktop/Test")
excelFiles = fileDir.rglob('*.xl*')
print(len(list(excelFiles)))
>>> 3
Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47
0

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
redystum
  • 352
  • 3
  • 10
0

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))
PangolinPaws
  • 670
  • 4
  • 10
0

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])
Arseny
  • 933
  • 8
  • 16
-1
import os
os.system('ls /etc | wc -l')

https://devconnected.com/how-to-count-files-in-directory-on-linux/

JieGH
  • 1
  • 1