开发者

Loop thru a directory and search in all pre-filtered XML files for a word

开发者 https://www.devze.com 2023-01-17 03:14 出处:网络
I would like to loop through a given directory and seach in all pre-filtered files for a search word. I prepared this c开发者_运维问答ode, but it is not looping thru all files, only

I would like to loop through a given directory and seach in all pre-filtered files for a search word. I prepared this c开发者_运维问答ode, 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?

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>


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


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()
0

精彩评论

暂无评论...
验证码 换一张
取 消