2013-10-19 4 views
1

파이썬 3에서 다음 코드를 실행하여 .txt 파일을 가져와 모든 두 번째 라인을 편집하고 편집 된 .txt 파일을 저장합니다. 그것은 작은 파일을 위해 잘 작동하지만, 내 파일은 ~ 2GB이며 너무 오래 걸립니다.성능 - 파이썬 텍스트 파일 편집 2GB 파일

효율성과 속도를 높이기 위해 코드를 변경하는 방법에 대한 제안 사항이 있습니까?

newData = "" 
i=0 
run=0 
j=0 
k=1 
seqFile = open('temp100.txt', 'r') 
seqData = seqFile.readlines() 
while i < 14371315: 
    sLine = seqData[j] 
    editLine = seqData[k] 
    tempLine = editLine[0:20] 
    newLine = editLine.replace(editLine, tempLine) 
    newData = newData + sLine + newLine 
    if len(seqData[k]) > 20: 
     newData += '\n' 
i=i+1 
j=j+2 
k=k+2 
run=run+1 
print(run) 

seqFile.close() 

new = open("new_temp100.txt", "w") 
sys.stdout = new 
print(newData) 
+0

관련 항목 : http://stackoverflow.com/questions/519633/lazy-method-for-reading-big-file-in-python. – Aleph

+1

아마도 루프 목록과'+ ='ing 대신에 문자열 목록을 만든 다음'' '.join (strings)'그들 목록을 만들어야합니다. http://stackoverflow.com/a/1967732/600110을 참조하십시오. –

+0

http://stackoverflow.com/questions/17034895/python-editing-a-single-line-in-a-large-text-file – megawac

답변

1

나는이 같은 제안 : 당신은 그냥 디스크에 직접 스트리밍 할 경우

# if python 2.x 
#from itertools import tee, izip 
# if python 3 
from itertols import tee 
# http://docs.python.org/2/library/itertools.html#recipes 
def pairwise(iterable): 
    "s -> (s0,s1), (s1,s2), (s2, s3), ..." 
    a, b = tee(iterable) 
    next(b, None) 
    # if python 2.x 
    #return izip(a, b) 
    return zip(a, b) 

new_data = [] 
with open('temp100.txt', 'r') as sqFile: 
    with open("new_temp100.txt", "w") as new: 
     for sLine, edit_line in pairwise(seqFile): 
      tmp_str = sLine + editLine[:20] 
      if len(sLine) > 20: 
       tmp_str = tmp_str + '/n' 
      new.write(tmp_str) 

그래서 당신은 전체를 보유 할 필요가 없습니다

# if python 2.x 
#from itertools import tee, izip 
# if python 3 
from itertols import tee 
# http://docs.python.org/2/library/itertools.html#recipes 
def pairwise(iterable): 
    "s -> (s0,s1), (s1,s2), (s2, s3), ..." 
    a, b = tee(iterable) 
    next(b, None) 
    # if python 2.x 
    #return izip(a, b) 
    return zip(a, b) 

new_data = [] 
with open('temp100.txt', 'r') as sqFile: 
    for sLine, edit_line in pairwise(seqFile): 
     # I think this is just new_line = tempLine 
     #tempLine = edit_line[:20] 
     #new_line = editLine.replace(editLine, tempLine) 
     new_data.append(sLine + editLine[:20]) 
     if len(sLine) > 20: 
      new_data.append('\n') 



with open("new_temp100.txt", "w") as new: 
    new.write(''.join(new_data)) 

당신은 아마 더 잘 할 수 있습니다 파일 내용을 메모리에 저장

+0

왜 파일을 읽고 문자열을 작성한 다음 파일에 모두 씁니다. 두 번 호출을 중첩하여 동시에 두 가지 작업을 수행 할 수 있습니다. 그런 다음 한 번에 각 결과 행을 작성하면됩니다. 이것이 더 빠를 것이라고 생각하십시오. –

+0

@TimDiggins 그것이 OP가하는 것입니다 ('sys.stdout = new'를 재설정함으로써) – tacaswell

+0

흠, 흥미 롭습니다. 하지만 다음과 같은 오류가 발생했습니다 : itertools import izip from ImportError : 이름 izip을 가져올 수 없습니다. –