suffa
suffa

Reputation: 3796

Writing the results of a search from a for loop to a file only give one line (one result)

I'm not understanding why I'm only getting the first match of word and ln in a logfile that I'm writing to in a loop (there are 50 or more matches). And and it's not well structured like when I print to the screen. Below is the code. Thanks!

Results in file that I'm writing: 343438363939 70642

regex = re.compile(r'(?:3\d){6}')
for root,dirname, files in os.walk(directory):
    for file in files:
        if file.endswith(".log") or file.endswith(".txt"):
            f = open(os.path.join(root,file))
                for i, line in enumerate(f.readlines()):
                    searchedstr = regex.findall(line)
                    ln = str(i)
                    for word in searchedstr:
                         print "\nString found: " + word
                         print "Line: " + ln
                         print "File: " + os.path.join(root,file)
                         print " "
                         logfile = open('result3.log', 'w')
                         logfile.write(word + '\n' + ln)
                         logfile.close()
            f.close()

Upvotes: 2

Views: 170

Answers (2)

zwol
zwol

Reputation: 140688

This is your problem:

                 logfile = open('result3.log', 'w')
                 logfile.write(word + '\n' + ln)
                 logfile.close()

Every time you open the log file like this, it erases everything that was in it before and starts writing from the beginning of the file. You can either change the open to

                 logfile = open('result3.log', 'a')

('a' stands for 'append'), or -- better -- open logfile just once, outside the outermost loop, like so:

regex = re.compile(r'(?:3\d){6}')
with open('result3.log', 'w') as logfile:
    for root, dirname, files in os.walk(directory):
        # ...
        logfile.write(word + '\n' + ln)

The with takes care of closing the file for you, so you don't need an explicit logfile.close(). (It would be better style to use a with to open f as well, if only so the f.close() isn't dangling there below the nested loops.) (Further addendum: enumerate(f.readlines()) is the same as enumerate(f) except slower.)

Upvotes: 4

Eric Fortin
Eric Fortin

Reputation: 7603

You're overwriting your output file everytime you're writing to it because you open it with 'w' instead of 'a' for appending.

Maybe you should open it once outside of the loop.

Upvotes: 2

Related Questions