简体   繁体   中英

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.

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

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))

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

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. Eg,

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM