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>The <code>del</code> is causing the problem. The <code>for</code> loop have no idea if you delete an element or not, so it always advances. There might be a hidden file in the directory, and it is the first element in the files. After it got deleted, the for loop skips one of the files and then reads the second one. To verify, you can print out the <code>files</code> and the <code>file</code> at the beginning of each loop. In short, <strong>removing the <code>del</code> line should solve the problem</strong>.</p>

<p>If this is a standalone script, bash might be more clean:</p>

<pre><code>count=0
for file in "$1"/*.txt; do
    echo -n "${count}: $(grep -o '[A-Z]' "$file" | tr "\n" ",") "
    ((count++))
done
</code></pre>

python regex loops operating-system