티스토리 뷰
[ 목표 ]
현재 바탕화면에 있는 파일들을 확장자별로
폴더를 나눠서 분류해보자!
1단계 : 압축파일이 있다면 압축을 풀고 정리
#현재 경로
import os
os.getcwd()
# 결과 : 'C:\\Users\\wlghk\\Desktop'
target_path = './바탕화면' # 바탕화면폴더 경로 설정
# 바탕화면에 있는 압축 파일 찾기
import glob
zipfile_path = []
for filename in glob.glob(os.path.join(target_path, '*.zip')):
zipfile_path.append(filename)
print(zipfile_path)
# 결과 : ['./바탕화면\\서울농수산시장관리 응시원서_경비_황석규.zip']
1-1. 압축 해제 (한글 깨짐)
for filename in zipfile_path:
with zipfile.ZipFile(filename) as myzip:
myzip.extractall('압축푼곳')
1-2. 파일 정보 (한글 깨짐)
for filename in zipfile_path:
with zipfile.ZipFile(filename) as myzip:
zipinfo = myzip.infolist()
print(zipinfo) # 압축 파일 안의 파일들 확인 -> 한글 깨져있음
# 결과
[<ZipInfo filename='░╟░¡║╕╟Φ.jpg' compress_type=deflate external_attr=0x20
file_size=1754158 compress_size=1749399>, <ZipInfo filename='░µ╖┬┴⌡╕φ╝¡(╚▓╝«▒╘).pdf'
compress_type=deflate external_attr=0x20 file_size=244035 compress_size=230365>,
<ZipInfo filename='╝¡┐∩│≤╝÷╗Ω╜├└σ░ⁿ╕« └└╜├┐°╝¡_░µ║±_╚▓╝«▒╘.hwp' compress_type=deflate
external_attr=0x20 file_size=332800 compress_size=310683>, <ZipInfo filename='└╠╝÷┴⌡╝¡.jpg'
compress_type=deflate external_attr=0x20 file_size=1727719 compress_size=1726446>]
1-3. 한글 깨짐을 방지하며 다시 압축 해제
# 한글 깨짐을 방지하며 다시 압축 해제
for filename in zipfile_path:
with zipfile.ZipFile(filename) as myzip:
zipinfo = myzip.infolist()
for info in zipinfo:
decode_name = info.filename.encode('cp437').decode('euc-kr')
# 한글 깨짐 방지
info.filename = os.path.join(target_path, decode_name) # 경로 설정
myzip.extract(info)
print(info)
# 결과
<ZipInfo filename='./바탕화면\\건강보험.jpg' compress_type=deflate external_attr=0x20 file_size=1754158 compress_size=1749399>
<ZipInfo filename='./바탕화면\\경력증명서(황석규).pdf' compress_type=deflate external_attr=0x20 file_size=244035 compress_size=230365>
<ZipInfo filename='./바탕화면\\서울농수산시장관리 응시원서_경비_황석규.hwp' compress_type=deflate external_attr=0x20 file_size=332800 compress_size=310683>
<ZipInfo filename='./바탕화면\\이수증서.jpg' compress_type=deflate external_attr=0x20 file_size=1727719 compress_size=1726446>
2. 파일명 정리해서 엑셀에 저장하기
!pip install openpyxl
import openpyxl as opx
def getFileName(target_path):
wb = opx.Workbook() # 엑셀파일 만들기
ws = wb.active # 작업모드
ws.cell(row=1, column=1).value = '파일경로'
ws.cell(row=1, column=2).value = '파일명(변경전)'
ws.cell(row=1, column=3).value = '파일명(변경후)'
i = 2
current_dir = target_path #'C:\\Users\\wlghk\\Desktop'
filelist = os.listdir(current_dir) # 바탕화면의 모든 파일명 저장
for filename in filelist:
ws.cell(row=i, column=1).value = current_dir + '/'
ws.cell(row=i, column=2).value = filename
i = i + 1
wb.save(os.path.join(target_path, '바탕화면파일list.xlsx'))
getFileName(target_path) # 바탕화면의 모든 파일명을 엑셀로 저장
2-1. 바탕화면에 지정한 이름으로 엑셀파일 생성됨
(바탕화면파일list.xlsx)
3. 파일명 변경하기
3-1. 엑셀에서 원하는 파일 이름 변경해서 저장
3-2. 튜플로 (디렉토리, 변경전파일, 변경후파일) 나열되는 리스트를 반환
def excelRead(filepath):
wb = opx.load_workbook(filepath)
ws = wb.active
dirpath = [r[0].value for r in ws] # 1열 '파일경로'의 모든 행이 저장
file_before = [r[1].value for r in ws] # 2열 '파일명(변경전)의 모든 행이 저장
file_after = [r[2].value for r in ws] # 3열 '파일명(변경후)의 모든 행이 저장
datalist =[]
for i in range(1, len(dirpath)): # 0행은 제목이므로 제외
temp = (dirpath[i], file_before[i], file_after[i]) # 튜플로 저장
datalist.append(temp) # 빈 리스트에 한 행씩 차례대로 추가
return datalist
rename_list = excelRead(os.path.join(target_path, '바탕화면파일list.xlsx'))
print(rename_list)
# 결과
[('./바탕화면/', 'Adobe Acrobat.lnk', 'Adobe Acrobat.lnk'),
('./바탕화면/', 'Apex 레전드™.url', 'Apex 레전드™.url'),
('./바탕화면/', 'Camtasia 9.lnk', 'Camtasia 9.lnk'), ...]
3-3. shutil 을 이용해 파일명 변경해주기
import shutil
def fileRename(datalist: list):
for data in datalist:
print(data[1] + '의 파일명을' + data[2] + '로 변경했습니다.')
shutil.move(data[0] + data[1], data[0]+ data[2])
fileRename(rename_list)
# 결과
Adobe Acrobat.lnk의 파일명을Adobe Acrobat.lnk로 변경했습니다.
Apex 레전드™.url의 파일명을Apex 레전드™.url로 변경했습니다.
Camtasia 9.lnk의 파일명을Camtasia 9.lnk로 변경했습니다.
Chrome.lnk의 파일명을Chrome.lnk로 변경했습니다.
DimScreen.exe의 파일명을DimScreen.exe로 변경했습니다.
Discord.lnk의 파일명을Discord.lnk로 변경했습니다.
GameLauncher.exe의 파일명을GameLauncher.exe로 변경했습니다.
4. 파일을 분류할 폴더 생성
4-1. 카테고리 이름 뽑아내기
def categoryList(target_path: str) -> list:
filelist = []
for filename in os.listdir(target_path):
filelist.append(filename)
category = []
for file in filelist:
temp_list = file.split('.')
category.append(temp_list[-1])
temp_set = list(set(category))
return temp_set
category_list = categoryList(target_path)
print(category_list)
# 결과
['mp4', 'gif', 'xlsx', 'pdf', 'url', 'docx', 'hwp',
'exe','lnk', 'png', 'mp3', 'txt', 'zip', 'jpg']
4-2. 뽑아낸 리스트로 폴더 생성
5. 파일 분류하기
import shutil
def moveFile(new_path:str, target_path:str, category_list:list):
dirlist = os.listdir(new_path) # 이동시킬 경로에 생성된 분류 list, './정리폴더/jpg'
filelist = os.listdir(target_path) # 이동시킬 파일명 리스트, './정리
categorydict = {}
for file in filelist:
try:
temp_list = file.split('.')
assert temp_list[-1] in category_list
# category_list -> ['mp4', 'gif', 'xlsx', 'pdf', 'url', ...]
categorydict[file] = temp_list[-1] # {'파일명' : '분류명'}
except:
categorydict[file] = '기타' # {'파일명' : '기타'}
for key, value in categorydict.items(): # 키와 밸류, 튜플 반환
shutil.copy(target_path + '/' + key, new_path + '/' + value)
# 예) './바탕화면/디스코드.Ink'
# -> './정리폴더/Ink' 로 복사
moveFile(new_path, target_path, category_list)
# 결과
( mp3 폴더 )
( pdf 폴더 )
폴더를 일일이 옮길 일이 있을 때는
이런 코드를 활용하면 쉽고 빠르게 파일 정리를 할 수 있을 것이다!!
( before )
( after )
'Python' 카테고리의 다른 글
29. DB를 이용한 단어장 만들기 (0) | 2024.03.28 |
---|---|
28. 파이썬과 MySQL 연동 (0) | 2024.03.28 |
26. (과제4) 영어 단어장 기능 추가 (1) | 2024.03.23 |
25. 디렉토리 관련 프로그램 (0) | 2024.03.22 |
24. 파이썬의 파일 입출력 라이브러리 (1) | 2024.03.22 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- FOR
- MySQLdb
- animation적용
- DB프로그램만들기
- 솔로의식탁
- __call__
- 변수
- 로또번호생성
- HTML
- 폼
- html이론
- CSS
- JavaScript
- 파이썬SQL연동
- Python
- 고정위치
- DB단어장
- MySQL
- 절대위치
- EPL정보프로그램
- Enclosing
- 줄 간격
- trasform
- 출력
- 박스사이징
- 셋
- 클래스문
- 닷홈
- 상대위치
- 리스트
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
글 보관함