2012-12-28 3 views
1

아래 코드에서 다음과 같은 문제가 있습니다. 어디에서 잘못되었는지 입력 해주십시오.파일 작업이 실패합니다.

  1. change_ignore_base.txt 및 change_ignore_base.txt가 생성되지 않고 어디로 잘못됩니까?

  2. chagne_ignore에 "\ r"과 "\ n"이 붙어있는 것을 볼 수 있습니다. 그들을 제거하고 나중에 검색에 사용할 수있는 변수에 넣는 것이 현명한 방법입니다.

change_ids.txt

206061 
150362 
147117 
147441 
143446 
200912 

change_ignore.txt

150362 
147117 
147441 
143446 
200914 

코드 여기

import os 
import subprocess 
from subprocess import check_call 

def sync (base_change): 
    # open a file 
    with open('change_ignore.txt') as f: 
     change_ignore = f.readlines() 
     print "change_ignore" 
     print change_ignore 

    with open('change_ids.txt') as f: 
     lines = f.readlines() 
     for line in lines: 
      line=line.strip() 
      print line 
      if line <= base_change: 
       print "IN line<=base_change" 
       print line 
       with open("change_ignore_base.txt", "a") as myfile: 
        myfile.write(line) 
      if line in change_ignore: 
       print "IN change_ignore" 
       print line 
       with open("change_ignore_file.txt", "a") as myfile: 
        myfile.write("line") 
      if line > base_change and line not in change_ignore: 
       pass 


def main(): 
    base_change=200913 
    sync(base_change) 

if __name__ == '__main__': 
    main() 
+0

당신의 조건이 충족되지 않은 추측. int와 int를 비교할 수 있습니다. btw, 그냥 "f.readlines()"또는 심지어 "for line in f"의 줄을 사용할 수 있습니다. – monkut

+0

@monkut - 예, 조건이 잘못되었습니다. 인쇄 문이 인쇄되지 않아서 분명히 볼 수 있습니다 ... 어디서 잘못 되었는가를 알아 내기 위해 somehelp가 필요합니다. – user1927396

+0

파일에서 행을 읽을 때 기본값으로 사용됩니다. 문자열로 읽습니다. 당신은 그것을 int와 비교할 필요가 있다면, 아마도 200913이라면, 입력 라인을 int로 변환 할 필요가 있는지를 확인하고 싶을 것이다. – monkut

답변

1

은 내가 믿는 프로그램에 가벼운 조정이 당신이 원하는 것을 달성한다 . 요점은 (주석에서 지적한 바와 같이) 정수를 정수와 비교하고 파일을 여러 번 열거 나 닫지 않도록해야한다는 것입니다 (파일 내부에서 반복문이 반복되는 경우).

import os 
import subprocess 
from subprocess import check_call 

def sync(base_change): 

    # Generate a list of integers based on your change_ignore file 
    with open('change_ignore.txt', 'rb') as f: 
     # Here we make a list of integers based on the file 
     change_ignore = [int(line.strip()) for line in f] 

    # Store your hits/misses in lists; that way you do not 
    # need to continuously open/close files while appending 
    change_ignore_base = [] 
    change_ignore_file = [] 

    # Now open the file of the IDs 
    with open('change_ids.txt', 'rb') as f: 
     # Iterate over the file itself 
     for line in f: 
      # Convert the line to an integer (note that this 
      # implicitly removes the newline characters) 
      # However we are going to write 'line' to our list, 
      # which will keep the newline (more on that later) 
      num = int(line) 
      print num 

      # Now we are comparing ints with ints 
      # I'm assuming the print statements are for debugging, 
      # so we offset them with some space, making it so that 
      # any relevant hits are indented under a number 
      if num <= base_change: 
       print " IN line<=base_change" 
       change_ignore_base.append(line) 
      if num in change_ignore: 
       print " IN change_ignore" 
       change_ignore_file.append(line) 
      if num > base_change and num not in change_ignore: 
       pass 

    # Now that you have lists containing the data for your new files, 
    # write them (they already have newlines appended so writelines works) 
    # You can use 'with' with two files in this way in Python 2.7+, 
    # but it goes over 80 characters here so I'm not a huge fan :) 
    with open('change_ignore_base', 'wb') as b, open('change_ignore_file', 'wb') as f: 
     b.writelines(change_ignore_base) 
     f.writelines(change_ignore_file) 


def main(): 
    base_change=200913 
    sync(base_change) 

main() 

이 파일을 만들고 다음을 인쇄해야합니다 :

206061 
150362 
    IN line<=base_change 
    IN change_ignore 
147117 
    IN line<=base_change 
    IN change_ignore 
147441 
    IN line<=base_change 
    IN change_ignore 
143446 
    IN line<=base_change 
    IN change_ignore 
200912 
    IN line<=base_change 
+0

고마워, 하나의 작은 의심,"change_ignore_file.txt "및"change_ignore_base.txt "파일을 삭제하고 싶습니다. 서브 루틴 시작시 os.remove를 사용할 계획이 있습니까? 다른 제안이 있습니까? – user1927396

+0

서브 루틴 시작시 os.remove를 사용하면 컴파일 오류가 발생합니다. "os.remove (change_ignore_base) UnboundLocalError : 로컬 변수 'change_ignore_base '할당 전에 참조 됨 " – user1927396

+1

@ user1927396 문제 없습니다. 파일을 지우는 것에 대해서는,'os.remove' shou 괜찮을거야. 그러나 원하지 않는다면 파일을 삭제할 필요는 없습니다. 쓰기 모드에서 파일을 열면 ('wb '로 표시) 파일을 자르고 새로운 내용을 쓸 것입니다. 그러므로 그것이 받아 들일 수 있다면, 위의 것이 효과가있다. 그러나 파일을 지우고 싶다면,'os.path' 파일을 찾은 다음 파일이 먼저 존재하는지 확인합니다 ('os.path.exists ('path/to'file')'); 그렇다면 파일의 문자열 이름을'os.remove'에 전달하여 제거합니다. 그게 도움이 되었으면 좋겠다 :) – RocketDonkey

관련 문제