본문으로 바로가기

참고: https://rfriend.tistory.com/429

import shutil
import os

image_dir = os.path.join(base_dir, 'images')
base_dir = os.path.join(base_dir, 'data')
split_dir = {split_name:os.path.join(base_dir,split_name)
                for split_name in ['train','valid','test']}

if os.path.exists(base_dir):
    shutil.rmtree(base_dir)  # rmtree는 삭제
os.mkdir(base_dir)  # 부모폴더는 있어야함, 중간 폴더까지 만들고싶으면 os.makedirs(base_dir)

for each_dir in split_dir.values():
    os.mkdir(each_dir)

 

 

os 기본함수

# 현재 경로 확인
os.getcwd()

# 작업경로 안 파일 리스트 확인
os.listdir(path)

# 작업경로 바꾸기
os.chdir(path)

# 경로 존재 유무 확인
os.path.isdir(path)

# 하위경로 만들기
os.path.join(base_dir, 'os')   # 'C:/Users/.../os'

 

1. 폴더 생성

os.mkdir(path)

 

2. 폴더 삭제

# 빈폴더 삭제
os.removedirs(삭제할 폴더 경로)
os.rmdir(삭제할 폴더 경로)  # os.remove(삭제할 파일)

# 파일 있는 폴더 삭제
shutil.rmtree(삭제할 폴더 경로)


# +폴더 경로 존재하는지 확인
os.path.isdir(폴더 경로)  # 경로 삭제했다면 False 반환

 

3. 파일/경로 이름 수정

os.rename(old_path, new_path)

 

4. 파일 복사

shutil.copyfile(src, dst)
# src: source directory
# dst: destination directory

 

5. Shutil 파일 확장자 변경

for i in range(100):
	# 확장자 변경
	shutil.copy('변경전{}{}.rpt'.format(index,i), '변경후{}{}.csv'.format(index,i))

	# 변경전 파일 삭제
	os.remove('변경전{}{}.rpt'.format(index,i))