2013-07-19 3 views
6

다음 스크립트를 작성하여 디렉토리의 모든 파일을 하나의 단일 파일로 결합했습니다.디렉토리의 모든 파일을 하나의 파일로 결합하는 python 스크립트

import time, glob 

outfilename = 'all_' + str((int(time.time()))) + ".txt" 

filenames = glob.glob('*.txt') 

with open(outfilename, 'wb') as outfile: 
    for fname in filenames: 
     with open(fname, 'r') as readfile: 
      infile = readfile.read() 
      for line in infile: 
       outfile.write(line) 
      outfile.write("\n\n") 
+7

시간에 최적화 되었습니까? "cat * .txt> all.txt"를 사용하십시오 :) –

+0

가능한 복제본 [여러 개의 텍스트 파일을 하나의 텍스트 파일로 결합하여 파이썬 사용] (http://stackoverflow.com/questions/17749058/combine-multiple-text-files- 하나의 텍스트 파일을 사용하는 파이썬) – llb

답변

23

사용 shutil.copyfileobj : 메모리에 전체를 읽지 않고 직접 파일 객체의 아이 네스,

import shutil 

with open(outfilename, 'wb') as outfile: 
    for filename in glob.glob('*.txt'): 
     if filename == outfilename: 
      # don't want to copy the output into the output 
      continue 
     with open(filename, 'rb') as readfile: 
      shutil.copyfileobj(readfile, outfile) 

shutiloutfile에 FileObject로 작성, 덩어리의 readfile 개체에서 읽기 직접. 줄 끝을 찾는 오버 헤드가 필요 없으므로 readline() 또는 반복 버퍼를 사용하지 마십시오.

읽기 및 쓰기 모두 동일한 모드를 사용하십시오. 이것은 Python 3을 사용할 때 특히 중요합니다. 두 가지 모두에 바이너리 모드를 사용했습니다.

+0

쓰기와 읽기에 동일한 모드를 사용해야하는 이유는 무엇입니까? –

+1

@JuanDavid : shutil은 하나의'.read()'호출을 사용하기 때문에, 다른 파일 객체에 대한'.write()'호출은 읽기 데이터를 다른 파일 객체로 전달합니다.바이너리 모드에서 열려 있으면 다른 하나는 텍스트에서 호환되지 않는 데이터 (바이너리 데이터를 텍스트 파일로 보내거나 텍스트 데이터를 바이너리 파일로 전달)를 통과합니다. –

0

당신은 반복 할 수 있습니다

이이

  1. 관용적 인 파이썬의 측면에서 최적화 할 수

  2. 여기에 시간

은 조각이다 내가 데이터를 복사 할

with open(fname, 'r') as readfile: 
    for line in readfile: 
     outfile.write(line) 
1

많은 변수를 사용할 필요가 없습니다.

with open(outfilename, 'w') as outfile: 
    for fname in filenames: 
     with open(fname, 'r') as readfile: 
      outfile.write(readfile.read() + "\n\n") 
1

fileinput 모듈은 여러 개의 파일

을 반복하는 자연적인 방법을 제공
for line in fileinput.input(glob.glob("*.txt")): 
    outfile.write(line) 
+0

한 번에 한 줄씩 읽는 것이 아니라면 더 좋을 것입니다. – Marcin

+0

@Marcin, 맞습니다. 필자는 Martijn Pieter의 "shutil.copyfileobj"humdinger를 보았을 때까지 이것이 멋진 해결책이라고 생각했습니다. – iruvar

1

파이썬 2.7을 사용하여, 내가 그랬어

shutil.copyfileobj(readfile, outfile) 

outfile.write(infile.read()) 

의 일부 "벤치 마크"테스트

63MB에서 313MB 크기의 20 개 .txt 파일을 반복 파일 크기 (~ 2.6GB)로 반복했습니다. 두 가지 방법 모두 정상 읽기 모드가 바이너리 읽기 모드보다 더 잘 수행되고 shutil.copyfileobj는 일반적으로 outfile.write보다 빠릅니다.

최고의 조합 최악의 조합 (outfile.write, 바이너리 모드) (shutil.copyfileobj, 정상 읽기 모드)을 비교할 때 차이가 매우 유의 한

:

outfile.write, binary mode: 43 seconds, on average. 

shutil.copyfileobj, normal mode: 27 seconds, on average. 

이 OUTFILE는 최종 크기를했다 2620MB의 일반 읽기 모드와 2578MB의 이진 읽기 모드.

+0

흥미 롭습니다. 그게 무슨 플랫폼 이었습니까? – ellockie

+0

필자는 Linux Fedora 16, 다른 노드 또는 Intel Core (TM) 2 Quad CPU Q9550, 2.83GHz를 사용하는 Windows 7 Enterprise SP1의 두 플랫폼에서 대략 작업합니다. 나는 그것이 후자라고 생각한다. –

+0

정보 주셔서 감사합니다! – ellockie

관련 문제