TransWikia.com

how to count number of file with a matching pattern using python

Stack Overflow Asked by Suryansh Mathur on February 16, 2021

import os, glob
HOME_FOLDER = 'path_to_directory'
pattern = '*2019*'
f = os.listdir(HOME_FOLDER)
c = 0;
for root, dirs, files in sorted(os.walk(HOME_FOLDER)):
    for file in files:
        if glob.fnmatch.fnmatch(file, pattern):
            c+=1
       
for name in f:
     print("Dir with ID", name, "has", c, "files of 2019")
        

Output

Dir with ID 69 has 10 files of 2019
Dir with ID 10 has 10 files of 2019
Dir with ID 1 has 10 files of 2019
Dir with ID 2 has 10 files of 2019
Dir with ID 13 has 10 files of 2019

The output gives only the total number of files. I want to have the number of files with the matching pattern.

Like this Dir with ID 20 has 3 files of 2019

Any help will be helpful.

2 Answers

Here's a solution using pathlib:

import pathlib

HOME_FOLDER = pathlib.Path('path_to_directory')
PATTERN = "*2019*"

for item in HOME_FOLDER.iterdir():
    if item.is_dir():
        matching_files = len(list([f for f in item.glob(f"**/{PATTERN}") if f.is_file()]))
        print("Dir with ID", item.name, "has", matching_files, "files of 2019")

Correct answer by chthonicdaemon on February 16, 2021

Try this.

c = 0
for root, dirs, files in sorted(os.walk(HOME_FOLDER)):
    c += len([file for file in files if ('2019' in file)])

Or, in a single line with list-comprehension:

sum([
    len([file for file in files if ('2019' in file)]) 
    for root, dirs, files in sorted(os.walk(HOME_FOLDER))
]

Common Code

You don't need to use glob for this purpose; os.walk would suffice alone.

import os
HOME_FOLDER = 'path_to_directory'
pattern = '2019' # note I am not using *2019*
f = os.listdir(HOME_FOLDER)

Answered by CypherX on February 16, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP