[python] 파이썬은 텍스트 파일을 연결

와 같은 20 개의 파일 이름 목록이 ['file1.txt', 'file2.txt', ...]있습니다. 이 파일을 새 파일로 연결하는 Python 스크립트를 작성하고 싶습니다. 으로 각 파일을 f = open(...)열고을 호출하여 한 줄씩 읽고 f.readline()새 줄에 각 줄을 쓸 수 있습니다. 그것은 나에게 매우 “우아한”것처럼 보이지 않습니다. 특히 한 줄씩 읽거나 써야하는 부분입니다.

파이썬에서 이것을하는 더 “우아한”방법이 있습니까?



답변

이거해야 해

큰 파일의 경우 :

filenames = ['file1.txt', 'file2.txt', ...]
with open('path/to/output/file', 'w') as outfile:
    for fname in filenames:
        with open(fname) as infile:
            for line in infile:
                outfile.write(line)

작은 파일의 경우 :

filenames = ['file1.txt', 'file2.txt', ...]
with open('path/to/output/file', 'w') as outfile:
    for fname in filenames:
        with open(fname) as infile:
            outfile.write(infile.read())

… 그리고 내가 생각한 또 다른 흥미로운 것 :

filenames = ['file1.txt', 'file2.txt', ...]
with open('path/to/output/file', 'w') as outfile:
    for line in itertools.chain.from_iterable(itertools.imap(open, filnames)):
        outfile.write(line)

안타깝게도이 마지막 방법은 GC가 처리해야하는 열린 파일 디스크립터를 남겨 둡니다. 난 그냥 재미 있다고 생각


답변

사용하십시오 shutil.copyfileobj.

그것은 당신을 위해 청크별로 입력 파일을 자동으로 읽습니다. 더 효율적이고 입력 파일을 읽는 것은 입력 파일 중 일부가 너무 커서 메모리에 맞지 않아도 작동합니다

import shutil

with open('output_file.txt','wb') as wfd:
    for f in ['seg1.txt','seg2.txt','seg3.txt']:
        with open(f,'rb') as fd:
            shutil.copyfileobj(fd, wfd)


답변

즉 무엇을 정확히 fileinput 함수 입니다 :

import fileinput
with open(outfilename, 'w') as fout, fileinput.input(filenames) as fin:
    for line in fin:
        fout.write(line)

이 유스 케이스의 경우 파일을 수동으로 반복하는 것보다 훨씬 간단하지 않지만 다른 경우에는 단일 파일처럼 모든 파일을 반복하는 단일 반복자를 갖는 것이 매우 편리합니다. (또한 fileinput각 파일이 완료 되 자마자 닫히게 된다는 사실은 필요 with하거나 각 파일이 필요하지 않다는 것을 의미 close하지만 이는 한 번의 비용 절감 일 뿐이며 큰 거래는 아닙니다.)

fileinput각 줄을 필터링하는 것만으로 파일을 적절하게 수정하는 기능과 같은 다른 유용한 기능 이 있습니다.


코멘트에 언급, 다른에서 설명하고있는 바와 같이 게시 , fileinput표시 파이썬 2.7에 대해 작동하지 않습니다. 코드를 파이썬 2.7과 호환되도록 약간 수정했습니다.

with open('outfilename', 'w') as fout:
    fin = fileinput.input(filenames)
    for line in fin:
        fout.write(line)
    fin.close()


답변

나는 우아함에 대해 모른다. 그러나 이것은 효과가있다.

    import glob
    import os
    for f in glob.glob("file*.txt"):
         os.system("cat "+f+" >> OutFile.txt")


답변

UNIX 명령의 문제점은 무엇입니까? (Windows에서 작업하지 않는 경우) :

ls | xargs cat | tee output.txt 작업을 수행합니다 (원하는 경우 하위 프로세스로 파이썬에서 호출 할 수 있음)


답변

outfile.write(infile.read()) # time: 2.1085190773010254s
shutil.copyfileobj(fd, wfd, 1024*1024*10) # time: 0.60599684715271s

간단한 벤치 마크는 셔틀의 성능이 더 우수하다는 것을 보여줍니다.


답변

@ inspectorG4dget 답변에 대한 대안 (2016 년 3 월 29 일 현재 최고 답변). 436MB의 3 개 파일로 테스트했습니다.

@ inspectorG4dget 솔루션 : 162 초

다음 해결책 : 125 초

from subprocess import Popen
filenames = ['file1.txt', 'file2.txt', 'file3.txt']
fbatch = open('batch.bat','w')
str ="type "
for f in filenames:
    str+= f + " "
fbatch.write(str + " > file4results.txt")
fbatch.close()
p = Popen("batch.bat", cwd=r"Drive:\Path\to\folder")
stdout, stderr = p.communicate()

아이디어는 “오래된 좋은 기술”을 활용하여 배치 파일을 작성하고 실행하는 것입니다. 세미 파이썬이지만 더 빨리 작동합니다. 창에서 작동합니다.