[파이썬] shutil을 이용한 특정 확장자 파일만 복사하기

파이썬의 shutil 라이브러리는 파일 및 디렉토리 작업을 위한 유용한 기능들을 제공합니다. 이 중 하나인 shutil.copy 함수를 사용하여 특정 확장자를 가진 파일만 선택적으로 복사하는 방법을 알아보겠습니다.

1. 필요한 라이브러리 import하기

import shutil
import os

shutilos 라이브러리를 필요로 합니다.

2. 원본 파일과 대상 디렉토리 경로 설정하기

src_dir = '/path/to/source_directory'
dest_dir = '/path/to/destination_directory'

src_dir 변수에는 원본 파일들이 위치한 디렉토리의 경로를 지정합니다. dest_dir 변수에는 선택적으로 복사할 파일들이 복사될 대상 디렉토리의 경로를 지정합니다.

3. 특정 확장자가 있는 파일만 복사하기

for file_name in os.listdir(src_dir):
    if file_name.endswith('.txt'):
        src_file = os.path.join(src_dir, file_name)
        dest_file = os.path.join(dest_dir, file_name)
        shutil.copy(src_file, dest_file)

os.listdir 함수를 사용하여 src_dir 디렉토리에 있는 모든 파일을 가져 옵니다. 그런 다음 endswith 메서드를 사용하여 파일명이 .txt로 끝나는지 확인합니다. 조건을 만족하는 파일의 경로를 src_file에 저장하고, dest_file 경로를 지정하기 위해 src_dirdest_dir 변수를 사용합니다. 마지막으로, shutil.copy 함수를 사용하여 파일을 복사합니다. 이 코드는 .txt 확장자를 가진 모든 파일을 대상 디렉토리로 복사합니다.

4. 마치며

shutil 라이브러리를 사용하여 특정 확장자를 가진 파일만 선택적으로 복사하는 방법을 알아보았습니다. 이를 응용해서 다른 확장자나 다른 조건으로 파일을 필터링하고 복사할 수도 있습니다. shutil의 다른 기능들을 살펴보면 여러 파일 및 디렉토리 작업에 유용하게 사용할 수 있습니다.

다음은 해당 코드의 전체 예시입니다.

import shutil
import os

src_dir = '/path/to/source_directory'
dest_dir = '/path/to/destination_directory'

for file_name in os.listdir(src_dir):
    if file_name.endswith('.txt'):
        src_file = os.path.join(src_dir, file_name)
        dest_file = os.path.join(dest_dir, file_name)
        shutil.copy(src_file, dest_file)

이를 통해 특정 확장자의 파일들을 간편하게 복사할 수 있습니다.