Python

Counting Instances of String in Multiple Files Using Python

This morning I came across a task which required me to count all instances of a particular element within multiple XML files in a directory.

Since the search was trivial enough, I decided to simply count instances of the element name instead of parsing the XML.  Below is the script I created.

import os

if __name__ == '__main__':

    #Directory containing files to search:
    directory = 'C:\\some_directory'

    count = 0
    for filename in os.listdir(directory):
        filepath = os.path.join(directory, filename)

        with open(filepath, 'r') as fp:
            for line in fp:
                #String to search for:
                count += line.count('<some_string>')

    print count