samedi 12 décembre 2020

Use Python Regex to search files and return filename

Please help. I'm searching several .txt files, in several directories for a pattern. If there is a match, I would like to print the filename and location of the match.

Here is my code:

a = ('Z:/rodney/020year/2020-04/')
b = []
for y in os.listdir(a):
    b.append(a+y+'/')

for filename in b:
    path = filename
    for filenames in listdir(path):
        with open(path+filenames) as currentfile:
            text = currentfile.read()
            loan = re.compile(r'2 NNN                            \d LOANS')
        bb = loan.search(text)
        with open('z:/rodney/results.txt','a') as f:
            f.write(os.path.dirname(path)+' ')
            f.write(filenames[:-4]+'\n')
            f.write(bb)

Error message = "TypeError: write() argument must be str, not None"

If there is a match, I would like to see only the filename and location of a match. I do not need to see "None" in every file where there is no match.

Aucun commentaire:

Enregistrer un commentaire