Q:

Python re.compile against all files in directory - not searching all files

I'm writing a Python 3.7.2 script that uses re.compile to search all files in a directory and returns every line in which a particular string appears. It works fine except for two problems:

There are several hundred files in the directory but the script only runs against the first 25.
It then re-runs against the first 25 indefinitely.

Any suggestions? Here's the script:
import os
import re

err_occur = []
pattern = re.compile(r"An important phrase")
path = "/users/mypath/"

for filename in os.listdir(path):
    try:
        with open(os.path.join(path, filename), encoding="UTF-8") as in_file:
            for linenum, line in enumerate(in_file):
                if pattern.search(line) != None:
                    err_occur.append((linenum, line.rstrip('\n')))
            for linenum, line in err_occur:
                print(line, sep='')
    except FileNotFoundError:
        print("Input file not found.")

A:

I think your problem may be with indentation.
I have moved some of the code and unindented the inner for loop. Try this code:
import os
import re

err_occur = []
pattern = re.compile(r"An important phrase")
path = "/users/mypath/"

for filename in os.listdir(path):

    try:
        with open(os.path.join(path, filename), encoding="UTF-8") as in_file:
            for linenum, line in enumerate(in_file):
                if pattern.search(line) != None:
                    err_occur.append((linenum, line.rstrip('\n')))
    except FileNotFoundError:
        print("Input file not found.")

for linenum, line in err_occur:
       print(line, sep='')

