R. Norm
R. Norm

Reputation: 21

Python loop not moving to next file

I am trying to traverse a directory, searching for all files containing the word 'Summary' in it's title. Once the file is found, I want to open the file and retrieve the lines with 'Audit Name' and 'Verified Hits' present. Also, retrieved the dirpath of the file.

My current codes searches a directory with 3 Summary files. Finds the dirpath and filenames, but only gets the contents from the first file, and prints that information three times.

import os
data_dir = "<dir with data>"

for dirpath, dirnames, filenames in os.walk(data_dir):
    for name in filenames:
        if 'Summary' in name:
            ofile = open(name, "r+")
            lines = ofile.readlines()
            ofile.close()
            for line in lines:
                if 'Audit Name:' in line:
                    audit_name = line
                if 'Verified Hits' in line:
                    verified_hits = line
            print(audit_name + verified_hits)

Upvotes: 2

Views: 155

Answers (1)

Jay Calamari
Jay Calamari

Reputation: 653

ofile = open(name, "r+")

Name is just the filename, and doesn't include the path. So you're opening the same path 3 times.

Try

ofile = open(os.path.join(dirpath, name), "r+")

Upvotes: 3

Related Questions