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:
Anthony is too cool for school. I Reported the criminal. I am Cool.
1: A, I, R, I, C
My second file contains the text:
Oh My initials are AK
And finally my 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()
Is there a way to loop through (and open) a list of files? Is it because I assign every File Object returned by open(os.path.join(filepath, file), 'r')
to the same name fileobj
?