본문 바로가기

코딩/파이썬 표준 라이브러리

[Python] 텍스트 파일 내용 복사 붙이기 - shutil.copyfileobj

python : standard library : shutil.copyfileobj

▶ 텍스트 파일 내용 복사 붙이기 - shutil.copyfileobj

임의 텍스트 파일의 내용을 작성할 때 파이썬 표준 라이브러리인 shutil 모듈의 copyfileobj 함수를 사용해 다른 텍스트 파일의 내용을 복사 붙여 넣을 수 있다.

 

copyfileobj 함수의 구성은 아래와 같다.

 

copyfileobj(fsrc, fdst, length=0)

 

파라미터 fsrc는 source 파일, fdst는 destination 파일, length는 copyfileobj 함수 내에서 한번에 복사되는 버퍼의 크기를 의미한다.

 

텍스트 파일 read.txt의 내용이 아래와 같은 경우,

 

In a Hong Kong warehouse, a swarm of autonomous robots works 24/7.
They're not just working hard, they're working smart; as they operate, they get better at their job.

 

다음의 코드는 write.txt란 이름의 텍스트 파일에 임의 내용을 작성하는 도중 read.txt 파일의 내용을 복사 붙여 넣는 코드이다.

 

# python 3.9.5
# shutil

import shutil

with open('write.txt', 'wt') as f_write:
    f_write.write('CNN\n')
    f_write.write('This swarm of robots gets smarter the more it works\n')
    f_write.write('June 16, 2021\n')
    f_write.write('\n')

    with open('read.txt', 'rt') as f_read:
        shutil.copyfileobj(f_read, f_write)

    f_write.write('\n')

    f_write.write('''The Autonomous Mobile Robots were developed by Chinese startup Geek+.
As they move around the warehouse they're guided by QR codes on the floor, and using
AI they are able to make their own decisions, including what direction to travel and
what route to take to their destination.''')

 

쓰기 속성의 파일 객체인 f_write와 읽기 속성의 파일 객체인 f_read를 copyfileobj 함수의 전달인자로 대입하여 텍스트 파일 read.txt의 내용을 write.txt 파일에 복사 붙여 넣는다.

 

위의 코드 실행으로 생성되는 write.txt 파일의 내용은 아래와 같으며, 텍스트 파일 중간에 read.txt 파일의 내용이 추가된 것을 볼 수 있다.

 

CNN
This swarm of robots gets smarter the more it works
June 16, 2021

In a Hong Kong warehouse, a swarm of autonomous robots works 24/7.
They're not just working hard, they're working smart; as they operate, they get better at their job.

The Autonomous Mobile Robots were developed by Chinese startup Geek+.
As they move around the warehouse they're guided by QR codes on the floor, and using
AI they are able to make their own decisions, including what direction to travel and
what route to take to their destination.