2017-04-06 2 views
-1

당신이 잘되기를 바랍니다. 파이썬 : 다른 txt 파일에서 하나의 txt 파일의 요소를 삭제하십시오.

나는 두 개의 TXT 파일이 있습니다 data.txt로하고

data.txt로 많은 라인을 가지고 있으며, 각 라인 사이에 공백이 여러 정수를 가지고 to_remove.txt. data.txt의 한 줄은 다음과 같습니다. 1001 1229 19910

to_remove.txt에 여러 줄이 있고 각 줄마다 하나의 정수가 있습니다. to_remove.txt의 한 줄은 다음과 같습니다. 1229

to_remove.txt에 정수가없는 data.txt가있는 새 txt 파일을 작성하고 싶습니다. data.txt의 각 행의 첫 번째 요소는 알고 있습니다. to_remove.txt의 요소가 없습니다. 그래서 to_remove.txt의 각 정수로 각 줄의 첫 번째가 아닌 요소를 모두 확인해야합니다.

이 코드를 작성했지만 코드가 너무 느립니다. data.txt에는 백만 줄 이상이 있고 to_remove.txt에는 수십만 줄이 있습니다.

더 빠른 방법을 제안 할 수 있다면 유용 할 것입니다.

with open('new.txt', 'w') as new: 
    with open('data.txt') as data: 
     for line in data: 
      connections = [] 
      currentline = line.split(" ") 
      for i in xrange(len(currentline)-2): 
       n = int(currentline[i+1]) 
       connections.append(n) 
      with open('to_remove.txt') as to_remove: 
       for ID in to_remove: 
        ID = int(ID) 
        if ID in connections: 
         connections.remove(ID) 
      d = '%d ' 
      connections.insert(0,int(currentline[0])) 
      for j in xrange(len(connections)-1): 
       d = d + '%d ' 
      new.write((d % tuple(connections) + '\n')) 
+0

현재 줄을 복사 할 필요가 없으며 처리중인 각 행에 대해 "to_remove"파일을 다시 읽을 필요가 없습니다 (처음 한 번 메모리에 저장).). –

답변

-1

내가 대답의 일부의 코드를 사용하여 내 질문에 대답 할 수있는 코드를 개발하고, 질문에 대한 코멘트에서 제안 :

여기 내 코드입니다.

def return_nums_remove(): 
    with open('to_remove.txt') as to_remove: 
     nums_to_remove = {item.strip() for item in to_remove} 
    return nums_to_remove 
with open('data.txt') as data, open('new.txt', 'w') as new: 
    nums_to_remove = return_nums_remove() 
    for line in data: 
     numbers = line.rstrip().split() 
     for n in numbers: 
      if n in nums_to_remove: 
       numbers.remove(n) 
     if len(numbers) > 1: 
      s = '%s ' 
      for j in xrange(len(numbers)-1): 
       s = s + '%s ' 
      new.write((s % tuple(numbers) + '\n')) 
관련 문제