2016-10-02 3 views
-1
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" 

텍스트 파일에 위 데이터가 있습니다. 설정 한 장치가 "Austin-Backup"인 경우에만 편집 XX에서 데이터를 추출하여 주석을 설정하려고합니다.텍스트 파일 내용 추출

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

아래는 내 코드입니다 :이 파일은 같은

출력이어야한다 편집 명령의 100 년대가 있습니다. 스트링 = "설정 디바이스"의 oldfile 라인

word = '"Austin-Backup"' 

import shutil 

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

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

는 :

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

만 라인의 Result.txt 아래 cript.txt가 갖는 코드를 실행 한 후 비어있다.

설정 코멘트 "Metronet"

+2

는 "그것은 작동하지 않습니다"유효한 문제 설명이 아니다. * 무엇이 작동하지 않습니까? 귀하의 질문을 편집하여 오류 또는 추적 목록의 ** 전체 텍스트 **를 포함하여 문제의 [mcve]를 게시하십시오. – MattDMo

+0

한 가지는 글에 들여 쓰기가 잘못되었습니다. 'for' 루프는'with' 문 안에 들어가려면 한 레벨 들여 쓰기해야합니다. – Charles

답변

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 

이 문제를 해결하는 데 더 효과적인 방법이있을 수 있지만.

편집 : 원래 buffer을 재설정 한 후 foundFalse으로 재설정하는 것을 잊어 버렸습니다. 이 최신 버전을 사용하고 있는지 확인하십시오. 또한 string은 일반적으로 나쁜 변수 이름입니다. 왜냐하면 Python은 내부적으로이를 사용하고 내용을 설명하지 않기 때문입니다.

+0

Omg ... 슈퍼 ... 코드가 완벽합니다 ... 파이썬을 처음 접했습니다. 네트워킹 용으로 파이썬을 사용합니다. 코드에 대해 많이 감사드립니다 ... :) – Bharath917

+0

@ Bharath917 물론입니다. 몇 가지 작지만 중요한 변화를 만들었으니이 최신 버전을 사용해야합니다. – Charles

+0

물론 .. 나는 버퍼링에 대해 몰랐고, 나는 그것을 배울 것입니다. 코드에 다시 한번 감사드립니다. – Bharath917

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