Python通过多行搜索文本

时间:2015-12-15 16:45:15

标签: python

import os
searchquery = 'word'
with open('Y:/Documents/result.txt', 'w') as f:
for filename in os.listdir('Y:/Documents/scripts/script files'):
    with open('Y:/Documents/scripts/script files/' + filename) as currentFile:
        for line in currentFile:
            if searchquery in line:
                start = line.find(searchquery)
                end = line.find("R")
                result = line[start:end]
                print result
                f.write(result + ' ' +filename[:-4] + '\n')

现在这适用于搜索" word"并且在单词之后打印所有内容,直到" R"假设它在同一条线上。但是,如果" R"它不会在它之前打印出来的东西。

例如:

this should not be printed!
this should also not be printed! "word" = 12345
6789 "R" After this R should not be printed either!

在上面的情况下,第3行的6789将不会打印出我的电流。但是我希望它是。我如何让python继续多行,直到它到达" R"。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

通常不会在下一行打印内容,因为您在一行中搜索该单词。更好的解决方案如下。

import os
searchquery = 'word'
with open('Y:/Documents/result.txt', 'w') as f:
    for filename in os.listdir('Y:/Documents/scripts/script files'):
        with open('Y:/Documents/scripts/script files/' + filename) as currentFile:              
            content = ''.join([line for line in currentFile])
            start = content.find(searchquery)
            end = content.find("R")
            result = content[start:end].replace("\n", "")
            print result
            f.write(result + ' ' +filename[:-4] + '\n')

请注意,这仅适用于单次出现。您将需要进一步分解以打印多个出现。