본문 바로가기
💻CODING/python

[py] 파일 및 폴더 정리하기

by 코딩하는 갓디노 2022. 9. 30.

[py] 파일 및 폴더 정리하기

 

예제는 스타트 코딩, 파이썬 크롤링 강의를 들으면서 공부한 내용입니다.

 

os 라이브러리

os라는 라이브러리를 사용하고, 내부 저장된 라이브러리로 별도 설치 필요 없습니다.

import os

 

폴더 생성,  폴더 내 파일 출력, 파일 확장자 출력

import os

# 폴더 만들기 - 상대 경로 이동
os.mkdir('test1')

# 폴더 만들기 - 상대 경로2 이동
os.mkdir('폴더이름/test2')

# 폴더 만들기 - 절대 경로 이동
os.mkdir('C:/project/python/test2')

# 파일 오른쪽 마우스 속성 > 위치 복사 -> 붙여넣기 후 역슬래시 슬래시로 바꿔주기
os.mkdir('C:/Users/PC CAFE/Downloads/images')

# 폴더가 없을때만 만들기
if not os.path.exists('C:/Users/PC CAFE/Downloads/images'):
   os.makedirs('C:/Users/PC CAFE/Downloads/images')

# 현재 폴더 내 모든 파일 출력
file_list = os.listdir('C:/Users/PC CAFE/Pictures/freepik/business')
print(file_list)

# 반복문을 통해 긱 파일의 확장자 추출
for file in file_list:
    name, ext = os.path.splitext(file)
    print(name, ext)

 

 

폴더 자동 정리

import os

# 정리할 확장자 리스트
extention_list = ['.jpg', '.png', '.gif']

# 정리할 폴더 
target = 'C:/Users/PC CAFE/Downloads'

# 만들 폴더
destination = target + "/images"

# 폴더가 없다면 만들기 
if not os.path.exists(destination):
    os.mkdir(destination)

# 현재 폴더 내 모든 파일 출력
file_list = os.listdir(target)

# 반복문을 통해 각 파일의 확장자 확인
for file in file_list:
     name, ext = os.path.splitext(file)
     if ext in extention_list:
        # 파일 이동
        source = os.path.join(target, file) # join(a, b)는 a/b 와 같이 슬래시로 이어줌
        os.rename(source,  os.path.join(destination, file))  # os.rename('원래 위치', '목적지')

 

구현화면

 

반응형

댓글