파이썬 기본 내장 모듈인 shutil 을 이용하면 된다
1. 파일 이동
import shutil
src_file_path = "data/aaa.txt"
dst_file_path = "tratin/data/bbb.txt"
shutil.move(src_file_path, dst_file_path)
2. 파일 복사
import shutil
src_file_path = "data/aaa.txt"
dst_file_path = "train/data/bbb.txt"
src_dir = "data/"
dst_dir = "train/data/"
# 복사되는 파일의 이름을 지정하는 경우
shutil.copyfile(src_file_path, dst_file_path)
# 파일을 특정 디렉토리로 복사
# 파일의 내용 복사
shutil.copy(src_file_path, dst_dir)
# 파일의 내용 및 권한 복사
shutil.copy2(src_file_path, dst_dir)
# 디렉토리의 내용, 권한 및 메타데이터까지 복사
shutil.copytree(src_dir, dst_dir)
3. 파일 삭제
import shutil
file_path = "data/aaa.txt"
shutil.rmtree(file_path, ignore_errors=True)
os 모듈을 이용하여 파일/디렉토리 삭제하려면 아래와 같다. 다만, 삭제가 안되는 상황에서는 FileNotFoundError, OSError 등이 발생하므로, 디렉토리를 완전 삭제하려면 shutil.rmtree()가 추천된다.
import os
# 디렉토리 삭제
os.rmdir('dir_name')
# 파일 삭제
os.remove('test.text')
끝-!
'Python' 카테고리의 다른 글
vscode black 자동 포매팅 설정 (0) | 2024.02.22 |
---|---|
파이썬 itertools 모듈 (1) | 2022.10.18 |
문자열의 구성(숫자, 알파벳) 판별 (0) | 2022.10.12 |
람다 함수(Lambda Function) (1) | 2022.10.12 |
댓글