파이썬에서 주로 사용하는 파일 복사 함수는 shutil 라리브러리의 copy, copy2, copyfile입니다.
사용방법은 shutil.copy( 소스 파일, 복사 파일) 이고,
아주 간단하게는 아래와 같은 형태로 사용할 수 있습니다.
import os
import shutil
if os.path.exists(src):
# src 존재하면 True
shutil.copy("C:\test.txt", "D:\test1.txt")
위 코드는 C 드라이브에 있는 test.txt 파일을 D 드라이브 test1.txt 파일로 복사하라는 내용입니다.
파일복사에 사용하는 함수가 3가지 정도 있는데, 차이점은 파일만 복사하는지, 파일 속성까지 복사하는지 여부입니다.
○ shutil.copyfile(src, dst) : 단순 파일 복사
○ shutil.copy(src, dst) : 단순 파일 복사 + 파일 권한(파일 읽기, 쓰기 권한) 복사( 리눅스의 chmode 개념)
○ shutil.copy2(src, dst) : 파일 복사 + 파일 속성 복사(파일 권한, 최근 접근 날짜, 최근 수정한 날짜 등)
단순복사?, 파일권한 필요, 파일 속성 필요 등 알맞게 사용하면 될듯 합니다.
파일 속성 복사 shutil.copy2를 이용하여 파일 복사하는 예는 아래 코드와 같고, 'c:\test.txt' 파일을 파일속성을 포함하여 'd:\ABC\test.txt' 에 복사하라는 예제입니다.
아래 코드를 잠깐 설명하자면, 기본 복사 코드에서
if not os.path.isfile(dst)로 복사위치에 해당 파일이 존재하는지 체크하고,
if not os.path.isdir(dst)로 복사위치에 해당 폴더가 없다면 생성하는 코드를 추가하였습니다.
import os
import shutil
src ="c:\\test.txt"
dst ="d:\\ABC\\test.txt"
# dst 파일이 없다면
if not os.path.isfile(dst):
# 복사할 곳에 디렉토리가 없다면
if not os.path.isdir(dst):
#디렉토리 경로 계산
dst_dir=os.path.dirname(dst)
#디렉토리 생성
os.makedirs(dst_dir)
#파일 복사
shutil.copy2(src, dst)
#종료
print("complete !!")
함수형태로 구현한 전체 코드는 아래와 같습니다. 메인 함수에서 대상파일, 복사할 위치만 정하면 될것 같습니다.
#!/usr/bin/env python
# -*- coding: utf8 -*-
import os
import shutil
src_path = ""
dst_path = ""
def file_copy(src, dst):
try:
if not os.path.isfile(dst):
if not os.path.isdir(dst):
dst_dir=os.path.dirname(dst)
os.makedirs(dst_dir)
shutil.copy2(src, dst)
print("complete !!")
#else:
# print("[OK]:"+src_path)
except Exception as e:
print(e)
print("[Error]:"+src)
if __name__ == "__main__":
# File Copy
src_path = "G:\\Driver\\NX-310\\test02.txt"
dst_path = "E:\\Driver\\FILE\\test02.txt"
file_copy(src_path, dst_path)
'공학속으로 > python' 카테고리의 다른 글
[python] IP 후이즈(whois) 조회하기 (0) | 2022.11.11 |
---|---|
[python] 크롬 브라우저에 저장된 패스워드 복호화 방법 (0) | 2022.10.27 |
[python] 파이썬 Visual Studio Code에서 개발 환경 구축 (0) | 2022.06.07 |
[python] 트위터 크롤링 (0) | 2022.05.26 |
[python] 텔레그램에 메세지 및 사진 보내기 (0) | 2022.04.26 |
댓글