2012-08-09 2 views
0

기본적으로 저장된 파일의 행을 새로운 업데이트 된 번호로 업데이트하려고하지만 파일에 한 줄만 남겨 둡니다. 파일을 업데이트하는 대신 전체 파일을 덮어 쓰는 것처럼 느껴집니다. 나는 다른 질문을 여기에서 보았고, 그들이 나를 사용하기에 적합한 모듈을 주었지만 나는 가지고있는 문제를 파악할 수없는 것처럼 보였다.개체가 입력 파일로 반복 가능하지 않음

unique = 1 
for line in fileinput.input('tweet log.txt', inplace=1): 
    if tweet_id in line: #checks if ID is unique, if it is not, needs to update it 
     tweet_fields = line.split(';') 
     old_count = tweet_fields[-2] 
     new_count = 'retweet=%d' % (int(tweet_retweet)) 
     line = line.replace(old_count, new_count) 
     print line 
     unique = 0 
if unique == 1:   #if previous if didn't find uniqueness, appends the file 
    save_file = open('tweet log.txt', 'a') 
    save_file.write('id='+tweet_id +';'+ 
        'timestamp='+tweet_timestamp+';'+ 
        'source='+tweet_source+';'+ 
        'retweet='+tweet_retweet+';'+'\n') 
    save_file.close() 

매우 쉬운 해결책이 있지만 분명히 실종 상태입니다. 미리 감사드립니다.

답변

0

나는 입력에 대한 루프의 조건에 따라 문제가 있다고 생각합니다. inplace=1 인수와 함께 fileinput.input을 사용하면 원래 파일의 이름을 "백업"확장명 (기본적으로 ".bak")으로 바꾸고 표준 출력을 원래 이름의 새 파일로 리디렉션합니다.

루프는 편집중인 행만 인쇄합니다. 이 때문에 일치하지 않는 모든 행이 파일에서 필터링됩니다. 일치하지 않는 경우에도 반복하는 각 행을 인쇄하여이 문제를 해결할 수 있습니다.

for line in fileinput.input('tweet log.txt', inplace=1): 
    if tweet_id in line: 
     tweet_fields = line.split(';') 
     old_count = tweet_fields[-2] 
     new_count = 'retweet=%d' % (int(tweet_retweet)) 
     line = line.replace(old_count, new_count) 
     unique = 0 
    print line 

이 유일한 변화는 if 블록 밖으로 print line 문을 이동 : 여기에 루프의 변경된 버전입니다.

관련 문제