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>Not sure what you were trying to use <code>shutil</code> to do. If you just want to copy a few lines, you can store them in a buffer, and when you reach the next <code>"edit"</code> line, copy the contents of the buffer to the output file.</p>

<pre><code>set_device = 'set device'
target = 'Austin-Backup'

with open('test.txt', 'r') as infile, open('result.txt', 'w') as outfile:
    buffer = []
    found = False
    for line in infile:
        if "edit" in line:
            # if buffer is worth saving
            if found:
                for line in buffer:
                    outfile.write(line)
            # reset buffer
            buffer = [line]
            found = False
        else:
            buffer.append(line)
        if set_device in line and target in line:
            found = True
</code></pre>

<p>Though there is likely a more efficient way of approaching the problem.</p>

<p>edit: I originally forgot to reset <code>found</code> to <code>False</code> after resetting <code>buffer</code>. Be sure you are using this latest version. Also <code>string</code> is generally a bad variable name because Python uses it internally, and because it isn't descriptive of its contents. </p>

python python-2.7