제 목적은
어느 한 폴더에 각각 모델명이 붙은 파일을 넣으면
자동으로 해당 모델 폴더로 가서 압축파일 안에 이동 시키는건데요
모델이 많아서 스크립트점 만들어 볼라고 하는 중 입니다.
파이썬 이고 모고 잘 모르고 그냥 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로 여기까진 짰는데
압축파일 안에 계속 중복으로 파일을 집어 넣고
압축파일 에 집어 넣고 남은 파일도 안지우고 냅두고 있네요
일단 폴더까진 잘 찾아가서 이동은 시킵니다.
해결해야 할게 압축 파일 내 중복된 파일을 처리해야 하는데
그런 코드를 적을떄 마다 프로세스가 엑세스 할 수 없다고 떠버림
층노숙자
그리고 gpt가 알려준대로 중복파일 처리 하게 해달라하면
예외가 발생했습니다. PermissionError
[WinError 32] 다른 프로세스가 파일을 사용 중이기 때문에 프로세스가 액세스 할 수 없습니다
요게 계속 뜸
뿌르드링
코드는 자세히 안봤으나 엑세스 거부 문제면 코드보단 권한의 문제일수있어요
실행을 윈도우면 관리자 권한으로해보시고, 리눅스면 su 권한으로 해보세요
층노숙자
네 감사합니다
tolabose
c드라이브 아래에 폴더 생성 안되지 않나?
층노숙자
그건 저번주에 해결했음 ㅋ
anywhere
오류가 뜨면 몇 번째 코드 라인에서 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"))
식으로 고치는 것이 맞지 않나 싶음.?..
확인은 안해봤으니 시도해보세요
층노숙자
고부분이 맞는거 같은데 관리자 권한으로 실행해도 안대네요
요거만 해결하면 되는데 어려움 ㅎㅎ
층노숙자
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}'를 삭제하는 데 실패했습니다.")
그냥 이렇게 처리 해야겠어요 압축파일 안에 중복파일 있으면 스킵하고
그냥 지워버리게 하니까 잘 돌아가긴 해서리 최신파일을 덮어 씌우면 좋긴한데 꼭 필요한 건 아니라서
요거에 만족해야 겠네요
ytrewq
모든 함수 시작부분에 함수 이름이랑 변수들 싸그리 로그파일에 저장시켜 달라고해 그래야 뭐가 뭔지 알거아니야. 글고 보통 중복파일은 만들고 제거가 아니고 애초에 만들지 않는게..
층노숙자
어쩔수없이 중복파일이 생기고 그걸 새로 덮어 씌어야 해서요 ㅠ
방구마렵다
c드라이브 바로 하위 폴더는 윈도우에서 권한좀 관리하는 듯 함
걍 이런 코드짤때는 d드라이브 등 다른 드라이브로 옮겨하면 맘 편함여
층노숙자
이것저것 수정해서
c드라이브에선 잘돌아가는데
정작 저걸돌릴 네트워크드라이버 에선
또 안대네요ㅠ
방구마렵다
저도 인트라넷에서 쓰는 비슷한 것 파이썬장고로 한적 있는데 전 파일서버에 ftp를 열고 ftp로 파일작업 했어요
층노숙자
음...아이피로 경로 설정 해보까요?
프린트 해보면 경로는 확실하게 인식 하드라고요
네트워크라 \\\\cccppp\\백업\\무슨방\\무슨방\\\\
요렇게 했거든요 인식은 잘 하는데 저 스크립트는 안돌아 가네요
방구마렵다
구글에 python samba file processing
방구마렵다
아마 방문권한 문제 일거에요
https://github.com/giampaolo/pyftpdlib
파이썬 삼바, 파이썬 FTP 이쪽으로 찾아보시면 될듯요
층노숙자
감사합니다~