Python

압축 파일 정리하기

hyunsik_park 2023. 3. 14. 17:12

import os
os.getcwd()

# 정리 대상 폴더 경로를 설정
target_path = './고라니'

 

# 압축 파일 확인
import glob

zipfile_path = []
for filename in glob.glob(os.path.join(target_path, '**/*.zip'), recursive=True):
    zipfile_path.append(filename)
    print(zipfile_path)
    

# 압축파일 해제
import zipfile
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)

 

2. 파일명 정리하기

!pip install openpyxl

import openpyxl as opx

# 폴더명 파일명을 입력받아 액셀 파일에 저장하는 함수
def getFileName(target_path):

  #  print(dir_list)

    wb = opx.Workbook()
    ws = wb.active # 새로 생성한 WorkBook의 활성화 시트를 ws로 정의
    
    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
    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, 'filelist.xlsx'))

getFileName(target_path)

 

3. 파일명 변경

def excelRead(filepath : str) -> list:
    wb = opx.load_workbook(filepath)
    ws = wb.active
    
    dirpath = [r[0].value for r in ws]
    file_before = [r[1].value for r in ws]
    file_after = [r[2].value for r in ws]
    
    len_num = len(dirpath)
    datalist = []
    
    for i in range(1, len_num):
        temp_tuple = (dirpath[i], file_before[i], file_after[i])
        datalist.append(temp_tuple)
        
    return datalist

rename_list = excelRead(os.path.join(target_path, 'filelist.xlsx'))
print(rename_list)

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)
    

 4. 폴더 생성하기

import fnmatch

def categoryList(target_path : str) -> list:
    file_list = []
    for filename in os.listdir(target_path):
        if fnmatch.fnmatch(filename, '*_[0-9][0-9][0-9].*'):
            file_list.append(filename)
            
    category =[]
    for file in file_list:
            
        temp_list = file.split('_')
        category.append(temp_list[-2])
    temp_set = set(category)
    result =list(temp_set)
    return result

categoryList(target_path)

categorylist = categoryList(target_path) +['기타']
print(categorylist)

 

import pathlib

 

new_path = './new_dir'
def makeDir(new_path:str, categorylist:list):
    for category in categorylist:
        new_dir = pathlib.Path(os.path.join(new_path, category))
        new_dir.mkdir(parents=True,exist_ok=True)
        

makeDir(new_path, categorylist)

 

5. 파일 분류 및 이동하기

import shutil

 

def moveFile(new_path, target_path, categorylist):
    dirlist = os.listdir(new_path) #이동시킬 경로에 생성된 분류 디렉토리 리스트
    filelist = os.listdir(target_path) # 이동시킬 파일명 리스트
    categorydic = {}
    
    for file in filelist:
        try:
            temp_list =file.split('_')
            assert temp_list[-2] in categorylist #카데고리가 맞지않으면 에러발생
            categorydic[file] = temp_list[-2] # {'파일명': '분류명'}
            
        except:
            categorydic[file] = '기타'# {'파일명': '기타'}
   # print(categorydic)
    for key, value in categorydic.items():
        shutil.copy(target_path+"/"+key, new_path+"/"+value)

 

moveFile(new_path, target_path, categorylist)

'Python' 카테고리의 다른 글

DAO,DTO,VO  (0) 2023.03.21
파일 읽기 및 저장하기  (0) 2023.03.14
변수 타입 어노테이션  (0) 2023.03.13
클로저(Closure)  (0) 2023.03.13
파일 입출력  (0) 2023.03.13