views:

29

answers:

2

Hello everyone,

I would like to loop thru a given directory and seach in all pre-filtered files for a search word. I prepared this code, but it is not looping thru all files, only the last file which was found is analyzed. Ideally all files should be analyzed and the output should be saved in a textfile. Could someone help? Thank you in advance!

import os, glob

for filename in glob.glob("C:\\test*.xml"):
    print filename

for line in open(filename):
    if "SEARCHWORD" in line:
        print line

The OUTPUT is looking like:

C:\test-261.xml
C:\test-262.xml
C:\test-263.xml
C:\test-264.xml
<Area>SEARCHWORD</Area>

Thank you!

+1  A: 

Indent the 2nd for-loop one more level to make it loop for every file found.

for filename in glob.glob("C:\\test*.xml"):
    print filename

#-->
    for line in open(filename):
        if "SEARCHWORD" in line:
            print line

BTW, since you are just iterating on the globbed result instead of storing it, you should use glob.iglob to save for duplicating the list. Also, it is better to put that open() in a with-statement so that the file can be closed properly even an exception is thrown.

for filename in glob.iglob('C:\\test*.xml'):
   print filename
   with open(filename) as f:
      for line in f:
         if 'SEARCHWORD' in line:
            print line
KennyTM
Cool, thank you for helping ! Thats it! Now I just have to save the output into a textfile.
Tom
A: 

You can also put the results in a file:

import os, glob
results = open('results.txt', 'w')
for filename in glob.glob("C:\test*.xml"):
    for line in open(filename):
        if "SEARCHWORD" in line:
            results.write(line)
results.close()
Radomir Dopieralski