Extract text file contents
<pre><code>edit 7
    set gateway 118.151.209.177
    set priority 1
    set device "port3"
    set comment "Yashtel"   

edit 56
    set dst 130.127.205.17 255.255.255.255
    set distance 5
    set device "Austin-Backup"
    set comment " www.scdhhs.gov"
edit 59
    set dst 10.100.100.0 255.255.252.0
    set distance 5
    set device "CityMD"
    set comment "Metronet"
</code></pre>

<p>The text file has above data i want to extract data from edit XX to set comment only if set device is "Austin-Backup". The file has 100's of edit commands </p>

<p>Output should should be like:</p>

<pre><code>edit 56
    set dst 130.127.205.17 255.255.255.255
    set distance 5
    set device "Austin-Backup"
    set comment " www.scdhhs.gov"
</code></pre>

<p>Below is my code.
    string = 'set device'</p>

<pre><code>word = '"Austin-Backup"'

import shutil

aa = open("result.txt", 'a')

with open('test.txt') as oldfile, open('cript.txt', 'r+') as new:
</code></pre>

<p>for line in oldfile:</p>

<pre><code>    new.write(line)

    new.write('\n')

    if string not in line:
        pass
    elif string in line:

        if word in line:

            shutil.copy('cript.txt','result.txt')

        elif word not in line:

            print line

            new.seek(0)

            new.truncate()
</code></pre>

<p>After executing the code the cript.txt has only below line and result.txt is empty. </p>

<p>set comment "Metronet"       </p>

<p>Here's another solution, just in case you were curious:</p>

<pre><code>target = 'set device "Austin-Backup"'
buffer = []
with open('test.txt') as infile and open('crypt.txt', 'w') as outfile:
    for line in infile:
        if not line.strip(): continue
        if line.startswith("edit"):
            outfile.write(''.join(buffer))
            buffer = [line]
            continue
        if not line.startswith('set device'):
            buffer.append(line)
        elif line.strip() == target:
            buffer.append(line)
        else:
            buffer = []
    outfile.write(''.join(buffer))
</code></pre>

python python-2.7