USER
import os
import pandas as pd
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
from threading import Thread
from datetime import datetime
def get_all_files_and_folders(drive, progress_callback):
"""지정한 드라이브 또는 폴더 내 모든 파일과 폴더 정보를 가져옵니다."""
drive = os.path.abspath(drive) # 경로를 절대 경로로 설정
items = []
try:
total_items = sum(len(files) + len(dirs) for _, dirs, files in os.walk(drive))
if total_items == 0:
progress_callback("set_max", 1)
progress_callback("update") # 최소 하나의 진행상황 업데이트를 위해
return items
progress_callback("set_max", total_items)
for root, dirs, files in os.walk(drive):
# 파일 정보 수집
for name in files:
file_path = os.path.join(root, name)
try:
file_size = os.path.getsize(file_path)
file_date = datetime.fromtimestamp(os.path.getmtime(file_path)).strftime('%Y-%m-%d %H:%M:%S')
file_type = os.path.splitext(name)[1] if os.path.splitext(name)[1] else "파일"
items.append((name, file_path, file_type, file_date, file_size))
except Exception as e:
print(f"파일 정보를 가져오는 중 오류 발생: {file_path} - {e}")
progress_callback("update")
# 폴더 정보 수집
for name in dirs:
dir_path = os.path.join(root, name)
try:
dir_date = datetime.fromtimestamp(os.path.getmtime(dir_path)).strftime('%Y-%m-%d %H:%M:%S')
items.append((name, dir_path, "폴더", dir_date, "N/A"))
except Exception as e:
print(f"폴더 정보를 가져오는 중 오류 발생: {dir_path} - {e}")
progress_callback("update")
except Exception as e:
print(f"전체 파일 및 폴더 정보를 가져오는 중 오류 발생: {e}")
return items
def export_to_excel(items, output_folder):
"""파일 및 폴더 목록을 엑셀로 내보냅니다."""
if not items:
messagebox.showinfo("결과", "추출된 파일 및 폴더가 없습니다.")
return None
df = pd.DataFrame(items, columns=['이름', '경로', '유형', '수정 날짜', '크기'])
output_file = os.path.join(output_folder, '파일_폴더_정보.xlsx')
try:
df.to_excel(output_file, index=False)
except Exception as e:
messagebox.showerror("오류", f"엑셀 파일 저장 중 오류가 발생했습니다: {e}")
return None
return output_file
def select_drive():
"""사용자가 검출할 드라이브 또는 폴더를 선택하도록 합니다."""
drive_selected = filedialog.askdirectory()
drive_path.set(drive_selected)
def select_output_folder():
"""엑셀 파일을 저장할 폴더를 선택하도록 합니다."""
folder_selected = filedialog.askdirectory()
output_folder_path.set(folder_selected)
def update_progress(action, value=None):
"""진행 상태를 업데이트합니다."""
if action == "set_max":
progress_bar["maximum"] = value
progress_bar["value"] = 0
elif action == "update":
progress_bar["value"] += 1
def run_extraction():
"""파일 및 폴더 정보를 추출하고 엑셀 파일로 저장합니다."""
drive = drive_path.get()
output_folder = output_folder_path.get()
if not drive or not output_folder:
messagebox.showwarning("경고", "드라이브와 폴더 경로를 모두 지정해 주세요.")
return
if not os.path.exists(drive):
messagebox.showerror("오류", "지정한 경로가 존재하지 않습니다.")
return
# 작업을 별도의 스레드에서 실행하여 GUI가 응답할 수 있도록 함
def task():
items = get_all_files_and_folders(drive, update_progress)
if items:
output_file = export_to_excel(items, output_folder)
if output_file:
messagebox.showinfo("완료", f"파일 및 폴더 정보가 {output_file}에 저장되었습니다.")
else:
messagebox.showinfo("결과", "폴더 내 파일 및 폴더가 발견되지 않았습니다.")
Thread(target=task).start()
# GUI 구성
root = tk.Tk()
root.title("파일 및 폴더 정보 추출기")
drive_path = tk.StringVar()
output_folder_path = tk.StringVar()
tk.Label(root, text="검출할 드라이브 또는 폴더 위치:").grid(row=0, column=0, padx=10, pady=10)
tk.Entry(root, textvariable=drive_path, width=50).grid(row=0, column=1, padx=10, pady=10)
tk.Button(root, text="드라이브/폴더 선택", command=select_drive).grid(row=0, column=2, padx=10, pady=10)
tk.Label(root, text="엑셀 파일 저장 폴더:").grid(row=1, column=0, padx=10, pady=10)
tk.Entry(root, textvariable=output_folder_path, width=50).grid(row=1, column=1, padx=10, pady=10)
tk.Button(root, text="폴더 선택", command=select_output_folder).grid(row=1, column=2, padx=10, pady=10)
progress_bar = ttk.Progressbar(root, orient="horizontal", length=400, mode="determinate")
progress_bar.grid(row=2, column=0, columnspan=3, padx=10, pady=20)
tk.Button(root, text="파일 및 폴더 정보 추출 실행", command=run_extraction).grid(row=3, column=0, columnspan=3, padx=10, pady=20)
root.mainloop() 해당 코드의 파이선파일을 pyinstaller --onefile --exclude-module matplotlib --exclude-module numpy 폴더내파일정보검색.py 커맨드를 실행하여 하나의 exe형식 실행파일 생성하고자 합니다. 모듈을 제대로 찾지 못해 문제가 발생하므로 가상환경을 만들어 이를 실행토록 하는 방식을 제안하여 개선된 코드와 명령어를 알려주시기 바랍니다.