Looping through (and opening) specific types of files in folder?
<p>I want to loop through files with a certain extension in a folder, in this case .txt, open the file, and print matches for a regex pattern. When I run my program however, it only prints results for one file out of the two in the folder:</p>

<blockquote>
  <p>Anthony is too cool for school. I Reported the criminal. I am Cool.</p>
</blockquote>

<pre><code>1: A, I, R, I, C
</code></pre>

<p>My second file contains the text:</p>

<blockquote>
  <p>Oh My initials are AK</p>
</blockquote>

<p>And finally my code:</p>

<pre><code>import re, os

Regex = re.compile(r'[A-Z]')
filepath =input('Enter a folder path: ')
files = os.listdir(filepath)
count = 0

for file in files:
    if '.txt' not in file:
        del files[files.index(file)]
        continue
    count += 1
    fileobj = open(os.path.join(filepath, file), 'r')
    filetext = fileobj.read()
    Matches = Regex.findall(filetext)
    print(str(count)+': ' +', '.join(Matches), end = ' ')
    fileobj.close()
</code></pre>

<p>Is there a way to loop through (and open) a list of files? Is it because I assign every File Object returned by <code>open(os.path.join(filepath, file), 'r')</code> to the same name <code>fileobj</code>?</p>

<p><strong>glob module</strong> will help you much more since you want to read files with specific extension.</p>

<p>You can directly get list of files with extension "txt" i.e. you saved one <strong>'if'</strong> construct.</p>

<p>More info on <a href="https://pymotw.com/2/glob/" rel="nofollow">glob module</a>.</p>

<p>Code will be less and more readable.</p>

<pre><code>import glob

for file_name in glob.glob(r'C:/Users/dinesh_pundkar\Desktop/*.txt'):
    with open(file_name,'r') as f:
        text = f.read()
        """
        After this you can add code for Regex matching,
        which will match pattern in file text.
        """
</code></pre>

python regex loops operating-system