Bharath917 Bharath917 - 2 months ago 17
Python Question

Extract text file contents

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"


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 130.127.205.17 255.255.255.255
set distance 5
set device "Austin-Backup"
set comment " www.scdhhs.gov"


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:

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


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

set comment "Metronet"

Answer

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:
                    new.write(line)
            # reset buffer
            buffer = [line]
            found = False
        else:
            buffer.append(line)
        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.

Comments