[파이썬] 파일 경로의 파일 이동 및 복사

파이썬은 파일 경로를 이용하여 파일을 이동하거나 복사하는 기능을 제공합니다. 이 기능을 사용하면 파일을 쉽게 이동하거나 복사할 수 있으며, 다양한 작업에 유용하게 활용할 수 있습니다.

파일 이동 (Move)

파일을 이동하기 위해서는 shutil 모듈의 move() 함수를 사용합니다. move() 함수는 이동할 파일의 경로를 첫 번째 매개변수로, 이동할 위치의 경로를 두 번째 매개변수로 전달합니다. 아래는 파일 이동의 예제 코드입니다.

import shutil

source_path = '/path/to/source/file.txt'
destination_path = '/path/to/destination/file.txt'

shutil.move(source_path, destination_path)

위 예제에서 source_path는 이동할 파일의 경로를 나타내고, destination_path는 이동할 위치의 경로입니다. move() 함수를 호출하면 source_path에 있는 파일이 destination_path로 이동됩니다.

파일 복사 (Copy)

파일을 복사하기 위해서는 shutil 모듈의 copy2() 함수를 사용합니다. copy2() 함수는 복사할 파일의 경로를 첫 번째 매개변수로, 복사될 위치의 경로를 두 번째 매개변수로 전달합니다. 아래는 파일 복사의 예제 코드입니다.

import shutil

source_path = '/path/to/source/file.txt'
destination_path = '/path/to/destination/file.txt'

shutil.copy2(source_path, destination_path)

위 예제에서 source_path는 복사할 파일의 경로를 나타내고, destination_path는 복사될 위치의 경로입니다. copy2() 함수를 호출하면 source_path에 있는 파일이 destination_path로 복사됩니다. copy2() 함수는 파일의 속성 및 타임스탬프를 보존합니다.

파일 이동 및 복사 예외 처리

파일 이동 및 복사 작업 중에 발생할 수 있는 예외를 처리하기 위해서는 try-except 구문을 사용합니다. 이를 통해 파일 작업 중에 에러가 발생하더라도 프로그램이 중단되지 않고 예외를 처리할 수 있습니다. 아래는 파일 이동 및 복사 중 예외 처리의 예제 코드입니다.

import shutil
import os

source_path = '/path/to/source/file.txt'
destination_path = '/path/to/destination/file.txt'

try:
    shutil.move(source_path, destination_path)
except Exception as e:
    print(f"파일 이동/복사 도중 에러가 발생했습니다: {e}")

위 예제에서는 try 블록 내에서 파일 이동 및 복사 작업을 시도하고, 예외가 발생하면 except 블록으로 제어가 이동합니다. 예외가 발생했을 때는 해당 예외를 e 변수에 담아 출력합니다. os 모듈을 사용하여도 비슷한 예외 처리를 수행할 수 있습니다.

위의 예제 코드를 참고하여 파일 경로의 파일 이동 및 복사를 쉽고 안전하게 수행할 수 있습니다. 따라서 이러한 기능을 통해 파일 작업을 효율적으로 처리할 수 있습니다.