Notice
Recent Posts
Recent Comments
Link
SeouliteLab
[Python/파이썬] 파일 복사하기 본문
예제:
def copy_file(source, destination):
try:
with open(source, 'rb') as f_source:
with open(destination, 'wb') as f_dest:
for line in f_source:
f_dest.write(line)
print("파일 복사가 완료되었습니다.")
except FileNotFoundError:
print("파일을 찾을 수 없습니다.")
except IOError:
print("파일을 복사하는 중 오류가 발생했습니다.")
source_file = "source.txt"
destination_file = "destination.txt"
copy_file(source_file, destination_file)
설명:
위의 코드는 파일을 복사하는 함수를 정의하고 호출하는 예제입니다.
copy_file
함수는 소스 파일과 대상 파일의 경로를 인자로 받습니다. 소스 파일을 바이너리 모드로 열어서 읽은 후, 대상 파일을 바이너리 모드로 열어서 소스 파일의 내용을 대상 파일에 쓰는 방식으로 파일을 복사합니다.
파일 복사 과정에서 예외가 발생할 수 있으므로 try-except
블록을 사용하여 예외를 처리합니다. FileNotFoundError는 파일을 찾을 수 없는 경우를 처리하고, IOError는 파일을 복사하는 동안 오류가 발생한 경우를 처리합니다.