source

Python에서 텍스트 파일을 연결하려면 어떻게 해야 하나요?

goodcode 2022. 10. 6. 21:36
반응형

Python에서 텍스트 파일을 연결하려면 어떻게 해야 하나요?

20개의 파일 이름 목록이 있는데['file1.txt', 'file2.txt', ...]이 파일들을 새로운 파일로 연결하기 위한 Python 스크립트를 작성하고 싶습니다.다음 방법으로 각 파일을 열 수 있습니다.f = open(...), 호출로 한 줄 한 줄 읽습니다.f.readline()각 행을 새 파일에 씁니다.특히 한 줄씩 읽고 써야 하는 부분은 그다지 우아하지 않은 것 같습니다.

Python에서 이것을 할 수 있는 더 "고상한" 방법이 있나요?

이것으로 충분합니다.

대용량 파일의 경우:

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에서 처리할 필요가 있습니다.난 그냥 그게 재밌다고 생각했어.

를 사용합니다.

입력 파일을 청크 단위로 자동으로 읽습니다.이것에 의해, 보다 효율적이고 입력 파일을 읽어낼 수 있습니다.또, 일부의 입력 파일이 메모리에 들어가지 않는 경우에서도 동작합니다.

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)

이것이 바로 파일 입력의 목적입니다.

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

이 사용 예에서는 파일을 수동으로 반복하는 것보다 훨씬 단순하지만, 다른 경우에는 모든 파일을 단일 파일처럼 반복하는 단일 반복기가 있으면 매우 편리합니다.fileinput각 파일이 완료되는 즉시 닫힙니다.with또는close단 한 줄의 비용절감일 뿐 큰 문제는 아닙니다.)

에는 다른 몇 가지 유용한 기능이 있습니다.fileinput예를 들어, 각 행을 필터링하는 것만으로 파일을 일괄적으로 변경할 수 있습니다.


댓글에 기재되어 있는 바와 같이, 또 다른 투고에서도 논의되고 있습니다.fileinputPython 2.7 용은 그림과 같이 동작하지 않습니다.Python 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")
outfile.write(infile.read()) # time: 2.1085190773010254s
shutil.copyfileobj(fd, wfd, 1024*1024*10) # time: 0.60599684715271s

간단한 벤치마크를 통해 shutil이 더 나은 성능을 발휘한다는 것을 알 수 있습니다.

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

ls | xargs cat | tee output.txt작업을 수행합니다(원하는 경우 하위 프로세스를 사용하여 python에서 호출할 수 있습니다).

디렉토리에 많은 파일이 있는 경우glob2파일명을 수동으로 쓰는 것보다 파일명 리스트를 생성하는 것이 좋을 수 있습니다.

import glob2

filenames = glob2.glob('*.txt')  # list of all .txt files in the directory

with open('outfile.txt', 'w') as f:
    for file in filenames:
        with open(file) as infile:
            f.write(infile.read()+'\n')

@inspectorG4dget 응답 대신 사용할 수 있습니다(일시 29-03-2016).436MB 파일 3개로 테스트했습니다.

@inspector G4dget 솔루션: 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()

아이디어는 "오래된 양호한 기술"을 활용하여 배치 파일을 생성하여 실행하는 것입니다.반피톤이지만 더 빨리 작동합니다.윈도우에 대응합니다.

File 객체의 .read() 메서드를 확인합니다.

http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects

다음과 같은 작업을 수행할 수 있습니다.

concat = ""
for file in files:
    concat += open(file).read()

또는 더 '더욱' python-way:

concat = ''.join([open(f).read() for f in files])

이 기사에 따르면 http://www.skymind.com/~ocrow/syslog_string/이 가장 빠릅니다.

파일이 크지 않은 경우:

with open('newfile.txt','wb') as newf:
    for filename in list_of_files:
        with open(filename,'rb') as hf:
            newf.write(hf.read())
            # newf.write('\n\n\n')   if you want to introduce
            # some blank lines between the contents of the copied files

이 너무 되지 않을 , 이되는 각 위해 은 이 알고리즘을 사용합니다.read(10000)예를들면.

def concatFiles():
    path = 'input/'
    files = os.listdir(path)
    for idx, infile in enumerate(files):
        print ("File #" + str(idx) + "  " + infile)
    concat = ''.join([open(path + f).read() for f in files])
    with open("output_concatFile.txt", "w") as fo:
        fo.write(path + concat)

if __name__ == "__main__":
    concatFiles()
  import os
  files=os.listdir()
  print(files)
  print('#',tuple(files))
  name=input('Enter the inclusive file name: ')
  exten=input('Enter the type(extension): ')
  filename=name+'.'+exten
  output_file=open(filename,'w+')
  for i in files:
    print(i)
    j=files.index(i)
    f_j=open(i,'r')
    print(f_j.read())
    for x in f_j:
      outfile.write(x)

언급URL : https://stackoverflow.com/questions/13613336/how-do-i-concatenate-text-files-in-python

반응형