2013-05-10 2 views
-1

일부 데이터를 다시 포맷하고 파이썬의 출력 파일에 저장하려고합니다. 원본에서 각 줄을 스트립() 한 다음 목록에 추가합니다. 원래 데이터에 추가해야하는 값으로 두 번째 목록을 만들고 (수정 사항은 원본 데이터를 묶음) 반복 된 값을 전달해야 할 때 문자열 형식 연산자를 사용하여 수정 된 데이터를 출력 파일에 기록합니다. 원래 데이터 목록. 출력은 출력의 각 레코드에 한 번만 표시되는 정보를 삽입해야하므로 1 : 1 출력이 아닙니다 (원본 줄부터 출력 줄까지). 그리고 이것이 제가 믿는 문제점에 부딪히는 곳입니다. 여기에 내 코드의 예입니다 ...반복 루프 내에서 문자열 서식 문제가 발생했습니다.

원본 데이터 :

Client 
#ofrecords(as an integer) 
Line1ofrecord1 
Line2ofrecord1 
.... 
Line1ofrecord2 
Line2ofrecord2 
.... 
End 

코드 :

def shouldbesimple(originalfile): 
    inputfile = open(originalfile, "r") 
    outputfile = open('finaloutput.txt', "w") 
    nowhitespace = originalfile.strip() 
    Client = nowhitespace.pop(0) 
    Counter = nowhitespace.pop(0) (each record has exactly the same number of lines) 

    #at this point only record information remains in list.. 

    Header = "stuff at beginning of each record in output" 
    Insertclient = "NEEDED {1} CHANGES" 
    Line1 = "THINGS I {0} MUST ADD" 
    Footer = "stuff at end of each record in output" 
    thingstoadd = [Header, Line1, Insertclient, Footer] 
    while counter > 0 : 
     writetofile = "" 
     for element in thingstoadd: 
      writetofile = element.format(nowhitespace.pop(0), Client) 
      outputfile.write(writetofile + "\n") 
     counter = counter - 1 
    inputfile.close() 
    outputfile.close() 

모든 내가 thingstoadd을 반복하기 시작 때까지 의도 한대로 작동합니다 ..

데이터가 의도 한대로 정렬되지 않고 "빈 목록에서 팝"오류가 발생합니다. writetofile을 인쇄하면 python이 {0}이 해당 요소에 나타날 때뿐만 아니라 모든 반복에서 형식 문으로 nowhitespace.pop(0) 연산을 실행하고 있음을 알 수 있습니다.

원래의 정보를 문자열 데이터로 전달하거나 모든 요소에서 .pop() 연산이 발생하지 않도록하는보다 적절한 방법이 있습니까?

+0

코드 블록 (들여 쓰기 네 개의 공간)에 코드를 넣어주십시오. 나는이 코드를 그대로 읽을 수 없다. – aestrivex

+0

닌자 편집을 해주셔서 감사합니다. 나는 내 자신을 제출하려고했을 때 나는 충격을 받았다. 이것은 나의 첫 번째 게시물이므로 적절한 예절 부족에 대해 사전에 사과드립니다. 가능한 한 빨리 질문에 대답하려고 노력합니다. –

+1

'nowhitespace = originalfile.strip()'을 어떻게 할 생각입니까? 'originalfile'은 당신의 파일 이름입니다. 그것은 '스트립 (strip)'이라고 불리는 것은 이상한 일이며, 심지어 나중에 그것을 꺼내려고 시도하는 것조차도 마찬가지입니다. –

답변

0

코드를 디버깅하는 대신, 내가하고 싶은 생각을 어떻게하는지 보여 드리겠습니다. 이 입력으로

import itertools 

# from itertools recipes in the docs 
def grouper(iterable, n, fillvalue=None): 
    "Collect data into fixed-length chunks or blocks" 
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx 
    args = [iter(iterable)] * n 
    return itertools.izip_longest(fillvalue=fillvalue, *args) 

def shouldbesimple(originalfile): 
    with open(originalfile) as inputfile, open('finaloutput.txt', "w") as outputfile: 
     client = next(inputfile).rstrip() 
     count = int(next(inputfile).rstrip()) 
     groups = grouper(inputfile, 4) 

     Header = "stuff at beginning of each record in output" 
     Insertclient = "NEEDED {1} CHANGES" 
     Line1 = "THINGS I {0} MUST ADD" 
     Footer = "stuff at end of each record in output" 
     thingstoadd = [Header, Line1, Insertclient, Footer] 

     for _ in range(count): 
      for fmt, line in zip(thingstoadd, next(groups)): 
       outputfile.write(fmt.format(line.rstrip(), Client) + '\n') 

:

Client 
2 
Line1ofrecord1 
Line2ofrecord1 
Line3ofrecord1 
Line4ofrecord1 
Line1ofrecord2 
Line2ofrecord2 
Line3ofrecord2 
Line4ofrecord2 
End 

나는이 출력을 얻을 :

THINGS I Line2ofrecord1 MUST ADD 
NEEDED Client CHANGES 
stuff at end of each record in output 
stuff at beginning of each record in output 
THINGS I Line2ofrecord2 MUST ADD 
NEEDED Client CHANGES 
stuff at end of each record in output 
+0

사실 작동합니다. 감사합니다! 필자는 python이 호출되는지 여부에 관계없이 .format (statement) 목록의 각 명령문 값을 검사한다는 사실에 놀랐습니다. –

관련 문제