提取文本文件内容

时间:2016-10-02 00:06:15

标签: python python-2.7

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"

文本文件具有以上数据我想从编辑XX中提取数据以仅在设置设备为" Austin-Backup"时设置注释。该文件有100个编辑命令

输出应该是:

edit 56
    set dst 130.127.205.17 255.255.255.255
    set distance 5
    set device "Austin-Backup"
    set comment " www.scdhhs.gov"

以下是我的代码。     string ='设置设备'

word = '"Austin-Backup"'

import shutil

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

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

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

执行代码后,cript.txt仅在行下面,result.txt为空。

设置评论" Metronet"

2 个答案:

答案 0 :(得分:0)

不确定您尝试使用shutil做什么。如果您只想复制几行,可以将它们存储在缓冲区中,当到达下一个"edit"行时,将缓冲区的内容复制到输出文件中。

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

虽然可能有更有效的方法来解决问题。

编辑:重置found后,我原本忘记将False重置为buffer。请确保您使用的是最新版本。另外string通常是一个错误的变量名称,因为Python在内部使用它,并且因为它不描述其内容。

答案 1 :(得分:0)

这是另一个解决方案,以防你好奇:

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