Bharath917 Bharath917 - 1 year ago 88
Python Question

Extract text file contents

edit 7
set gateway
set priority 1
set device "port3"
set comment "Yashtel"

edit 56
set dst
set distance 5
set device "Austin-Backup"
set comment ""
edit 59
set dst
set distance 5
set device "CityMD"
set comment "Metronet"

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

Output should should be like:

edit 56
set dst
set distance 5
set device "Austin-Backup"
set comment ""

Below is my code.
string = 'set device'

word = '"Austin-Backup"'

import shutil

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

with open('test.txt') as oldfile, open('cript.txt', 'r+') as new:

for line in oldfile:



if string not in line:
elif string in line:

if word in line:


elif word not in line:

print line


After executing the code the cript.txt has only below line and result.txt is empty.

set comment "Metronet"

Answer Source

Not sure what you were trying to use shutil to do. If you just want to copy a few lines, you can store them in a buffer, and when you reach the next "edit" line, copy the contents of the buffer to the output file.

set_device = 'set device'
target = 'Austin-Backup'

with open('test.txt', 'r') as oldfile, open('result.txt', 'w') as new:
    buffer = []
    found = False
    for line in oldfile:
        if "edit" in line:
            # if buffer is worth saving
            if found:
                for line in buffer:
            # reset buffer
            buffer = [line]
            found = False
        if set_device in line and target in line:
            found = True

Though there is likely a more efficient way of approaching the problem.

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download