2017-12-15 10 views
0

두 파일의 크기가 같지 않은 file1file2과 적어도 각각 return separated 줄이 있습니다. file1의 콘텐츠를 file2와 (과) 일치시키고 싶은 경우 일치하는 것이 있으면 file1에서 해당 콘텐츠를 삭제하십시오. 예 :두 번째 파일에 포함 된 첫 번째 파일에서 줄 제거

+------------+-----------+--------------------------+ 
| file1  | file2  | after processing - file1 | 
+------------+-----------+--------------------------+ 
| google.com | in.com | google.com    | 
+------------+-----------+--------------------------+ 
| apple.com | quora.com | apple.com    | 
+------------+-----------+--------------------------+ 
| me.com  | apple.com |       | 
+------------+-----------+--------------------------+ 

내 코드가 보인다.

with open(file2) as fin: 
     exclude = set(line.rstrip() for line in fin) 

for line in fileinput.input(file1, inplace=True): 
     if line.rstrip() not in exclude: 
      print 
      line, 

그냥 file1의 모든 내용을 삭제합니다. 어떻게 해결할 수 있습니까? 감사합니다. .

+0

작업 메모리에 적어도 하나의 파일을 보관하기에 충분한 RAM이 있습니까? – zwer

+0

@zwer 예. 1 개는 16 기가 있습니다. 나는 그것이 충분해야한다고 생각한다. –

답변

2

print 문과 해당 인수는 별도의 줄에 있습니다. 대신 print line,을 수행하십시오.

+0

젠장! 허용되는대로 즉시 수락합니다. 파이썬 2는 악합니다. 그냥'print (line.rstrip()) '을 사용하여 완벽하게 작동 시켰습니다. 같은 것을 추가하십시오. –

0

작업 메모리에 문제가없는 경우, 나는 원액 좋을 것 - file2을로드 한 후 일치하는 라인 아래로 쓰는 file1 반복 :

import os 
import shutil 

FILE1 = "file1" # path to file1 
FILE2 = "file2" # path to file2 

# first load up FILE2 in the memory 
with open(FILE2, "r") as f: # open FILE2 for reading 
    file2_lines = {line.rstrip() for line in f} # use a set for FILE2 for fast matching 

# open FILE1 for reading and a FILE1.tmp file for writing 
with open(FILE1, "r") as f_in, open(FILE1 + ".tmp", "w") as f_out: 
    for line in f_in: # loop through the FILE1 lines 
     if line.rstrip() in file2_lines: # match found, write to a temporary file 
      f_out.write(line) 

# finally, overwrite the FILE1 with temporary FILE1.tmp 
os.remove(FILE1) 
shutil.move(FILE1 + ".tmp", FILE1) 

편집 : 분명히, fileinput.input()을 당신의 문제가 오타 였기 때문에 거의 똑같이하고 있습니다. 오 잘, 후손에 대한 대답을 남겨두면 전체 프로세스를보다 잘 제어 할 수 있습니다.

+0

['fileinput.input (inplace = True)'] (https://docs.python.org/2/library/fileinput.html#fileinput.input) 문서를보십시오. 그의 코드는'file1'을 수정하고 있습니다. –

+1

@ Robᵩ - 하, 나는 그것을 몰랐다. 매일 새로운 것을 배웁니다. 그에 따라 내 대답을 업데이트했습니다. – zwer