2013-03-20 1 views
1

데이터가 약 3MB 이상인 파일 (예 : file1.txt)이 있다고 가정합니다. 이 데이터를 두 번째 파일 (예 : file2.txt)에 기록하려면 다음 방법 중 어느 것이 더 좋을까요?파이썬에서 파일을 읽고 쓰는 더 나은 접근법은 무엇입니까?

언어 사용 : 파이썬 2.7.3

접근 한 :

file1_handler = file("file1.txt", 'r') 
for lines in file1_handler: 
    line = lines.strip() 
    # Perform some operation 
    file2_handler = file("file2.txt", 'a') 
    file2_handler.write(line) 
    file2_handler.write('\r\n') 
    file2_handler.close() 
file1_handler.close() 

접근법 2을 :

file1_handler = file("file1.txt", 'r') 
file2_handler = file("file2.txt", 'a') 
for lines in file1_handler: 
    line = lines.strip() 
    # Perform some operation 
    file2_handler.write(line) 
    file2_handler.write('\r\n') 
file2_handler.close() 
file1_handler.close() 

내가 방금 때문에 접근 방식이 더 좋을 것이라고 생각 열기 및 닫기 file2.txt 한 번. 너 무슨 소리 야?

+2

[파일] (http://docs.python.org/2/)이 아닌 [공개] (http://docs.python.org/2/library/functions.html#open) 파일을 엽니 다. library/functions.html # file). – Matthias

답변

6

사용 with, 그것은 당신을 위해 자동으로 파일을 닫습니다 :

with open("file1.txt", 'r') as in_file, open("file2.txt", 'a') as out_file: 
    for lines in in_file: 
     line = lines.strip() 
     # Perform some operation 
     out_file.write(line) 
     out_file.write('\r\n') 

사용 open 대신 filefile이되지 않습니다.

당연히 file1의 모든 줄마다 file2를 열어도 좋지 않습니다.

+1

나는 똑같은 것을 쓰고 있었다 :) @Hemant,보세요 : http://docs.python.org/2/whatsnew/2.5.html#pep-343-the-with-statement –

+0

f2.write ('\ r \ n ') :이 작업을 수행하려면 f2를 이진 파일로 열어야합니다 (플래그에 "b"를 추가). –

+0

oops! 나는 open이 더 이상 사용되지 않을 것이라고 생각했다 : p (나는 제대로 문서를 읽지 않았다) 그래서 쓰기 속도가 빨라지 는가? 접근 방식 1은 1 MB의 데이터를 복사하는 데 거의 2 시간이 걸렸기 때문입니다. – Hemant

0

저는 최근에 비슷한 것을하고있었습니다 (당신을 잘 이해한다면). 방법 :

file = open('file1.txt', 'r') 
file2 = open('file2.txt', 'wt') 

for line in file: 
    newLine = line.strip() 

    # You can do your operation here on newLine 

    file2.write(newLine) 
    file2.write('\r\n') 

file.close() 
file2.close() 

이 접근 방식은 매력처럼 작동합니다! (파벨 Anossov + 버퍼링에서 파생 된)

+0

: cool .. 접근 방식에 대해 감사합니다. – Hemant

0

내 솔루션 :

dim = 1000 
buffer = [] 
with open("file1.txt", 'r') as in_file, open("file2.txt", 'a') as out_file: 
    for i, lines in enumerate(in_file): 
     line = lines.strip() 
     # Perform some operation 
     buffer.append(line) 
     if i%dim == dim-1: 
      for bline in buffer: 
       out_file.write(bline) 
       out_file.write('\r\n') 
      buffer = [] 

파벨 Anossov 먼저 적합한 솔루션을 준 : 이것은 단지 제안이다) 는 아마이 기능을 구현하는 더 우아한 방법이 존재한다. 누구든지 알고 있으면 알려주십시오.

+0

@ Francesco :이 답변을 주셔서 감사합니다. :) 그러나 메소드를 열거하는 데 익숙하지 않습니다. 열거 형을 사용하여 얻을 수있는 이점을 설명해 주시겠습니까? – Hemant

+0

@Hemant : enumerate가 유용합니다. 여기를보십시오. http://docs.python.org/2/library/functions.html#enumerate –

+0

@ Francesco : 의사에게 감사드립니다. 이제 나는 당신의 모범을 더 분명히 이해합니다. :) – Hemant