시나리오 :
윈도우에서 파일들을 다운로드 받을 때, 따로 경로를 지정하지 않는 이상, 윈도우의 기본 다운로드 폴더로 저장된다.
중요한 파일이거나, 용량이 큰 파일일 경우, 바로 정리하는 경우도 있지만
보통 한 번 열어본 후, 사용할 일이 없는 파일들이나, 프로그램 설치를 위한 설치프로그램 등등 다운로드 폴더에 파일들이 쌓이게 된다.
간혹, 다시 필요한 파일들이 생각나, 다운로드 받은 기억이 있어, 다운로드 폴더를 찾아봤지만, 너무 파일이 많아 찾기 어렵거나, 파일 이름을 까먹어서 검색기능을 사용하기에 어려울 때, 그냥 새로 다운로드를 받은 기억이 있어, 다운로드 폴더를 정리하는 프로그램을 만들기로 한다.
- 기존 윈도우 다운로드 폴더에서, 사용자가 지정한 폴더 경로를 입력받아, 해당 폴더에 파일들을 정리한다.
- 파일은 종류에 따라 분리하며, 각각의 하위 폴더를 생성하여 정리한다.
- 음악파일, 문서파일, 동영상파일, 압축된파일, 실행파일, 사진파일
- 나머지파일들은 '기타'폴더에 저장
import os
import glob
import shutil
class CleanDowndir :
def __init__(self): # 정리할 폴더의 종류별 확장자 지정
self.picli = ['*.jpg', '*.png', '*.bmp', '*.gif']
self.orgzipli = ['*.zip', '*.rar', '*.tar', '*.egg', '*.7z', '*.war', '*.alz']
self.videoli = ['*.mp4', '*.avi', '*.mkv', '*.wmv', '*.mov', '*.flv', '*.asf', '*.mpg', '*.mpeg', '*.webm', '*.smi', '*.srt']
self.musicli = ['*.mp3', '*.wav', '*.flac']
self.documentli = ['*.txt', '*.pdf', '*.hwp', '*.xls', '*.xlsx', '*.ppt', '*.doc', '*.docx', '*.pptx']
self.exeli = ['*.exe']
self.otherli = ['*']
def run(self): # 실행용 함수
while True:
username = input('다운로드 폴더 지정을 위해, 윈도우 사용자 폴더명을 입력해주세요. : ')
self.download_path = 'C:/Users/' + username + '/Downloads'
if os.path.exists(self.download_path): # 경로가 존재하는지 확인
break
else:
print("경로를 찾을 수 없습니다. 사용자명을 다시 확인해주세요.")
while True:
newdirpath = input('파일들을 정리할 폴더 경로를 입력해주세요. : ')
self.new_path = newdirpath.strip().replace('\\', '/') # 윈도우에서 경로가 \로 되어있어 / 로바꾸기, 공백제거
if os.path.exists(newdirpath): # 경로가 존재하는지 확인
self.new_path = newdirpath
break
else:
print("입력한 경로가 존재하지 않습니다. 다시 입력해주세요.")
# 쭈욱 실행
self.pic()
self.orgzip()
self.video()
self.music()
self.docnument()
self.exe()
self.other()
def pic(self): # 사진파일 정리
a =[]
for file in self.picli: # 해당 종류의 확장자들을 찾아서 리스트에 담음
a.extend(glob.glob(os.path.join(self.download_path, file)))
for filename in a: # 리스트에 있는 파일들을 다운로드 폴더에서 복사해서 옮긴 후, 기존 다운로드 폴더에 있는 파일들은 삭제
os.makedirs(self.new_path+'./사진', exist_ok=True) # 해당 폴더에 하위 폴더를 만듬, 이미 있으면 pass
shutil.copy(filename, self.new_path + './사진') # 파일들 복사
os.remove(filename) # 다운로드 폴더에 남있는 원본파일 삭제
def orgzip(self): # 압축된 파일 (안푼 원본파일) 정리
a =[]
for file in self.orgzipli:
a.extend(glob.glob(os.path.join(self.download_path, file)))
for filename in a:
os.makedirs(self.new_path+'./압축파일', exist_ok=True)
shutil.copy(filename, self.new_path + './압축파일')
os.remove(filename)
def video(self): # 동영상 파일 정리
a =[]
for file in self.videoli:
a.extend(glob.glob(os.path.join(self.download_path, file)))
for filename in a:
os.makedirs(self.new_path+'./동영상', exist_ok=True)
shutil.copy(filename, self.new_path + './동영상')
os.remove(filename)
def music(self): # 음악 파일 정리
a =[]
for file in self.musicli:
a.extend(glob.glob(os.path.join(self.download_path, file)))
for filename in a:
os.makedirs(self.new_path+'./음악', exist_ok=True)
shutil.copy(filename, self.new_path + './음악')
os.remove(filename)
def docnument(self): # 문서 파일 정리
a =[]
for file in self.documentli:
a.extend(glob.glob(os.path.join(self.download_path, file)))
for filename in a:
os.makedirs(self.new_path+'./문서', exist_ok=True)
shutil.copy(filename, self.new_path + './문서')
os.remove(filename)
def exe(self): # 실행 파일 정리
a =[]
for file in self.exeli:
a.extend(glob.glob(os.path.join(self.download_path, file)))
for filename in a:
os.makedirs(self.new_path+'./실행파일', exist_ok=True)
shutil.copy(filename, self.new_path + './실행파일')
os.remove(filename)
def other(self): # 나머지 파일 기타 파일로 정리함
a =[]
for file in self.otherli:
a.extend(glob.glob(os.path.join(self.download_path, file)))
for filename in a:
os.makedirs(self.new_path+'./기타', exist_ok=True)
try:
# 파일인 경우
if os.path.isfile(filename):
shutil.copy(filename, self.new_path + './기타')
os.remove(filename)
# 폴더인 경우
elif os.path.isdir(filename):
newfolder = os.path.join(self.new_path + './기타', os.path.basename(filename))
shutil.copytree(filename, newfolder)
shutil.rmtree(filename)
except PermissionError: # 가아끔 사용자의 권한에 따라 이동이 안되는 폴더가 있으면 오류 메세지 출력
# 내 pc로 테스트 중, 간혹 발생해서, 해당 부분먼저 예외처리 했습니당
print('권한이 없어, 폴더들은 정리되지 않아, 다운로드 폴더에 그대로 남습니다.')
print('정리가 완료되었습니다.')
start = CleanDowndir()
start.run()
'파이썬' 카테고리의 다른 글
재귀 호출(recursive call) (0) | 2024.03.29 |
---|---|
디렉토리 관리 프로그램 (1) | 2024.03.23 |
파일 입출력 라이브러리 (0) | 2024.03.22 |
변수 타입 어노테이션 (0) | 2024.03.22 |
파일 입출력 (0) | 2024.03.22 |