프로그래밍

파이썬 코드점 봐주실분 계신가요?

제 목적은

어느 한 폴더에 각각 모델명이 붙은 파일을 넣으면

자동으로 해당 모델 폴더로 가서 압축파일 안에 이동 시키는건데요

 

모델이 많아서 스크립트점 만들어 볼라고 하는 중 입니다.

파이썬 이고 모고 잘 모르고 그냥 gpt 켜놓고 하는 중인데 

계속 막히네요

 

import os

import shutil

import zipfile

import time

 

source_folder = "c:\\0_자동\\"

destination_folder = "c:\\0_백업\\"

 

# 폴더가 존재하지 않으면 생성하는 함수

def create_folder_if_not_exists(path):

    if not os.path.exists(path):

        os.makedirs(path)

 

# source_folder 안의 파일들을 검색하여 이동시키는 함수

def move_files():

    files = os.listdir(source_folder)

    for file in files:

        file_path = os.path.join(source_folder, file)

        if os.path.isfile(file_path):

            # 파일명에서 "_"를 기준으로 모델명 추출

            if "_" in file:

                model_name = file.split("_")[0]

            else:

                continue  # "_"가 없는 파일은 이동하지 않음

 

            # 모델명을 기반으로 폴더 경로 생성

            model_folder = find_model_folder(model_name)

 

            # 모델 폴더가 없으면 생성

            create_folder_if_not_exists(model_folder)

 

            # plot 폴더 경로 생성

            plot_folder = os.path.join(model_folder, "plot")

 

            # plot 폴더가 없으면 생성

            create_folder_if_not_exists(plot_folder)

 

            # 파일 복사

            dest_path = os.path.join(plot_folder, file)

            if os.path.exists(dest_path):

                os.remove(dest_path)

            shutil.copy2(file_path, dest_path)

 

            # 원본 파일 삭제

            os.remove(file_path)

 

            # plot.zip 압축 파일 업데이트

            update_zip_archive(plot_folder)

 

# 모델명과 일치하는 폴더를 검색하는 함수

def find_model_folder(model_name):

    for root, _, _ in os.walk(destination_folder):

        for folder in os.listdir(root):

            if model_name in folder:

                return os.path.join(root, folder)

 

    # 일치하는 폴더가 없을 경우 모델명으로 폴더 생성

    return os.path.join(destination_folder, model_name)


 

# 압축 파일 내에 파일 존재 여부 확인하는 함수

def file_exists_in_zip(zip_file, file):

    try:

        zip_file.getinfo(file)

        return True

    except KeyError:

        return False

 

# 압축 파일 내의 파일 제거하는 함수

def remove_file_in_zip(zip_file, file):

    temp_zip_path = os.path.join(zip_file.filename + '.tmp')

    with zipfile.ZipFile(zip_file.filename, 'r') as source_zip, zipfile.ZipFile(temp_zip_path, 'w') as temp_zip:

        for item in source_zip.infolist():

            if item.filename != file:

                temp_zip.writestr(item, source_zip.read(item.filename))

 

    os.remove(zip_file.filename)

    os.rename(temp_zip_path, zip_file.filename)

 

# plot.zip 압축 파일 업데이트하는 함수

def update_zip_archive(plot_folder):

    zip_path = os.path.join(plot_folder, "plot.zip")

 

    if not os.path.exists(zip_path):

        # 압축 파일이 없는 경우 새로 생성

        with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED, allowZip64=True) as zip_file:

            pass

 

    # 중첩된 압축 파일 검사

    with zipfile.ZipFile(zip_path, "r") as zip_file:

        if "plot.zip" in zip_file.namelist():

            # 중첩된 압축 파일이 있는 경우 제거

            zip_file.extract("plot.zip", path=plot_folder)

            os.remove(os.path.join(plot_folder, "plot.zip"))

 

    # plot 폴더 내 파일들 추가

    files = os.listdir(plot_folder)

    with zipfile.ZipFile(zip_path, "a", zipfile.ZIP_DEFLATED, allowZip64=True) as zip_file:

        for file in files:

            file_path = os.path.join(plot_folder, file)

            if os.path.isfile(file_path) and file != "plot.zip":

                zip_file.write(file_path, file)

 

    # 임시 압축 파일 삭제

    temp_zip_path = os.path.join(plot_folder, "plot_tmp.zip")

    if os.path.exists(temp_zip_path):

        os.remove(temp_zip_path)


 

# 파일 이동 함수 실행

move_files()

 

일단 gpt로 여기까진 짰는데

압축파일 안에 계속 중복으로 파일을 집어 넣고 

압축파일 에 집어 넣고 남은 파일도 안지우고 냅두고 있네요

 

일단 폴더까진 잘 찾아가서 이동은 시킵니다.

 

해결해야 할게  압축 파일 내  중복된 파일을 처리해야 하는데

 

그런 코드를 적을떄 마다 프로세스가 엑세스 할 수 없다고 떠버림

17개의 댓글

2023.05.24

그리고 gpt가 알려준대로 중복파일 처리 하게 해달라하면

 

예외가 발생했습니다. PermissionError

[WinError 32] 다른 프로세스가 파일을 사용 중이기 때문에 프로세스가 액세스 할 수 없습니다

 

요게 계속 뜸

0
2023.05.24

코드는 자세히 안봤으나 엑세스 거부 문제면 코드보단 권한의 문제일수있어요

실행을 윈도우면 관리자 권한으로해보시고, 리눅스면 su 권한으로 해보세요

0
2023.05.24
@뿌르드링

네 감사합니다

0
2023.05.24

c드라이브 아래에 폴더 생성 안되지 않나?

0
2023.05.24
@tolabose

그건 저번주에 해결했음 ㅋ

0
2023.05.24

오류가 뜨면 몇 번째 코드 라인에서 permission error가 뜨는지 확인할 수 있을 거임.

느낌에는 압축 파일 내 중첩 확인하는 코드에서 plot.zip 파일을 열고 압축 해제한 다음, 해당 압축 파일을 삭제하기 때문에 생기는 거 같은데, 파이썬에서 이미 plot.zip 파일을 zipfile.Zipfile로 열어서 읽고 있는 상태이기 때문에 파일 사용 중이라고 뜨는 것 같음.

 

# 중첩된 압축 파일 검사

 

with zipfile.ZipFile(zip_path, "r") as zip_file:

if "plot.zip" in zip_file.namelist():

# 중첩된 압축 파일이 있는 경우 제거

zip_file.extract("plot.zip", path=plot_folder)

os.remove(os.path.join(plot_folder, "plot.zip"))

부분을

 

# 중첩된 압축 파일 검사

with zipfile.ZipFile(zip_path, "r") as zip_file:

if "plot.zip" in zip_file.namelist():

# 중첩된 압축 파일이 있는 경우 제거

zip_file.extract("plot.zip", path=plot_folder)

zip_file.close()

os.remove(os.path.join(plot_folder, "plot.zip"))

 

식으로 고치는 것이 맞지 않나 싶음.?..

확인은 안해봤으니 시도해보세요

0
2023.05.24
@anywhere

고부분이 맞는거 같은데 관리자 권한으로 실행해도 안대네요

 

요거만 해결하면 되는데 어려움 ㅎㅎ

0
2023.05.24
@anywhere

def move_to_plot_zip(plot_folder, file_path):

zip_path = os.path.join(plot_folder, "plot.zip")

file_name = os.path.basename(file_path)

 

with zipfile.ZipFile(zip_path, "a", zipfile.ZIP_DEFLATED, allowZip64=True) as zip_file:

if file_name not in zip_file.namelist(): # 압축 파일에 중복된 파일이 없는 경우에만 처리

zip_file.write(file_path, arcname=file_name, compress_type=zipfile.ZIP_DEFLATED)

 

try:

os.remove(file_path) # 파일 이동 후 원본 파일 삭제

except PermissionError:

print(f"PermissionError: 파일 '{file_path}'를 삭제하는 데 실패했습니다.")

 

그냥 이렇게 처리 해야겠어요 압축파일 안에 중복파일 있으면 스킵하고

그냥 지워버리게 하니까 잘 돌아가긴 해서리 최신파일을 덮어 씌우면 좋긴한데 꼭 필요한 건 아니라서

요거에 만족해야 겠네요

0
2023.05.24

모든 함수 시작부분에 함수 이름이랑 변수들 싸그리 로그파일에 저장시켜 달라고해 그래야 뭐가 뭔지 알거아니야. 글고 보통 중복파일은 만들고 제거가 아니고 애초에 만들지 않는게..

0
2023.05.24
@ytrewq

어쩔수없이 중복파일이 생기고 그걸 새로 덮어 씌어야 해서요 ㅠ

0
2023.05.29

c드라이브 바로 하위 폴더는 윈도우에서 권한좀 관리하는 듯 함

걍 이런 코드짤때는 d드라이브 등 다른 드라이브로 옮겨하면 맘 편함여

0
2023.05.29
@방구마렵다

이것저것 수정해서

c드라이브에선 잘돌아가는데

정작 저걸돌릴 네트워크드라이버 에선

또 안대네요ㅠ

0
2023.05.29
@층노숙자

저도 인트라넷에서 쓰는 비슷한 것 파이썬장고로 한적 있는데 전 파일서버에 ftp를 열고 ftp로 파일작업 했어요

0
2023.05.29
@방구마렵다

음...아이피로 경로 설정 해보까요?

프린트 해보면 경로는 확실하게 인식 하드라고요

네트워크라 \\\\cccppp\\백업\\무슨방\\무슨방\\\\

요렇게 했거든요 인식은 잘 하는데 저 스크립트는 안돌아 가네요

0
2023.05.30
@층노숙자

구글에 python samba file processing

0
2023.05.30
@층노숙자

아마 방문권한 문제 일거에요

https://github.com/giampaolo/pyftpdlib

파이썬 삼바, 파이썬 FTP 이쪽으로 찾아보시면 될듯요

0
2023.05.30
@방구마렵다

감사합니다~

0
무분별한 사용은 차단될 수 있습니다.
번호 제목 글쓴이 추천 수 날짜 조회 수
5710 [프로그래밍] 아 ssl 적용햇는데 개정신없네 9 넌또화나있네 0 9 시간 전 151
5709 [프로그래밍] 패스트 캠퍼스 <---- 얘내는 가격 인상 원툴임? 5 조강현 0 3 일 전 293
5708 [프로그래밍] 클라가 파이썬 셀레니움같은거 써서 클릭하고 그러는걸 감지 ... 5 리옴므 0 4 일 전 207
5707 [프로그래밍] leetcode 50일 달성 1 JimmyMcGill 1 4 일 전 184
5706 [프로그래밍] 그냥 개인공부용 git 만들건데 5 년째재수강 0 4 일 전 268
5705 [프로그래밍] html 자바스크립트 질문 19 책걸이 0 4 일 전 313
5704 [프로그래밍] 아니 시바 이게 무슨일이야 4 인간지표 0 5 일 전 327
5703 [프로그래밍] 아두이노 키트 아무것도 모르고 사도 될까? 6 그것 0 5 일 전 264
5702 [프로그래밍] 횽들 Vimeo에 올라가있는 동영상의 원본크기를 확인할 수 있... 13 카뜨만두 0 6 일 전 187
5701 [프로그래밍] c# 이벤트와 델리게이트 13 RX7900XTX 0 8 일 전 307
5700 [프로그래밍] Aws 람다에 파이썬 올려서 결과 받아오는데 11 아르피쥐 0 10 일 전 345
5699 [프로그래밍] 마리아DB mediumtext 그냥 쓰고 싶은데 21 잉텔 0 11 일 전 222
5698 [프로그래밍] 안드로이드 씹뉴비 질문이요 2 집에가게해줘 0 11 일 전 129
5697 [프로그래밍] c언어 7년했는데 이런게 되는거 처음알았음.. 4 케로로중사 0 12 일 전 903
5696 [프로그래밍] 파이썬 1도 모르는데 GPT로 프로그램 뚝딱 만듬 2 푸르딩딩 1 15 일 전 753
5695 [프로그래밍] 담주 면접잡혔는데 8 삐라루꾸 0 16 일 전 506
5694 [프로그래밍] 아두이노 부트로더를 구웠는데.. 4 렙이말한다ㅡ니가옳다 0 16 일 전 236
5693 [프로그래밍] IOS 개발자 있나여? 1 g4eng 0 18 일 전 261
5692 [프로그래밍] 시스템 디자인 인터뷰 준비 도움좀!!! 1 Nognhyup 0 19 일 전 205
5691 [프로그래밍] 최근에 vscode 쓴 사람 도움! 3 172102 0 20 일 전 530