본문 바로가기

카테고리 없음

디렉토리 관리프로그램 과제

디렉토리 관리프로그램을 이용하여 파일 분류 저장해보기.

 

 

 

import os
import glob
import zipfile
import shutil
import fnmatch
import pathlib

위의 코드는 모듈을 import하는 부분입니다. 각 모듈은 다음과 같은 역할을 합니다:

  • os: 운영체제와 상호작용하기 위한 여러 함수를 제공합니다.
  • glob: 파일 경로를 패턴 매칭하여 찾는 데 사용됩니다.
  • zipfile: ZIP 파일을 읽고 쓰는 데 사용됩니다.
  • shutil: 파일 및 디렉토리 작업을 위한 여러 함수를 제공합니다.
  • fnmatch: 파일 이름을 패턴으로 매칭하는 데 사용됩니다.
  • pathlib: 파일 경로를 객체로 다루는 데 사용됩니다.
target_path = './정리'

정리 대상의 디렉토리 경로를 설정한다.

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

정리 디렉토리 파일에서 압축을 푼다.

for filename in zipfile_path:
    with zipfile.ZipFile(filename) as myzip:
        zipinfo = myzip.infolist()
        # print(zipinfo) # 압축 파일 정보
        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)

압축파일 해제도 진행해보았다.

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
    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'))

파일경로와 정리할 이름을 정해준다.

wb = opx.load_workbook(os.path.join(target_path, 'filelist.xlsx'))
ws = wb.active
dirpath = [r[0].value for r in ws]
file_before = [r[1].value for r in ws]
def excelRead(filepath):
    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]
    datalist = []
    # for i in zip(dirpath, file_before, file_after):
    #     datalist.append(i)
    len_num= len(dirpath)
    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)

엑셀파일 정리한 내용을 출력해보자.

def categoryList(target_path):
    file_list = []
    for filename in os.listdir(target_path):
        # A_2022_01_13_부서로그_인사_001.pdf
        if fnmatch.fnmatch(filename,'*_[0-9][0-9][0-9].*'):
            file_list.append(filename)
    category =[]
    for file in file_list:
        temp_list = file.split('_') # ['A','2022','01','13','부서로그','인사','001.pdf']
        category.append(temp_list[-2])
    category = set(category)
    return list(category)

생산,물류,엑셀 등 이름에 맞게 따로 분류해준다.

categoryList(target_path)
['생산', '물류', '인사', 'ERD', '클래스설계']

다음과 같이 분류된다.