红穆笔记
首頁 › 語言筆記 › python配合winrar進行指定文件夾,批量打包
語言筆記 python

python配合winrar進行指定文件夾,批量打包

python配合winrar进行指定文件夹,批量打包

最近折騰出來的,用起來還不錯。
備份一下。

免得下次找不到。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json
import re
import subprocess
import os
import sys
from pathlib import Path

WWW_ROOT = Path(r"D:\phpstudy_pro\WWW")
DATA_JSON = WWW_ROOT / "data.json"
OUTPUT_DIR = Path(r"C:\Users\18102\Desktop\pbootcms源碼文件夾")
PASSWORD = "www.4s5.cn"
WINRAR_PATH = r"C:\Program Files\WinRAR\WinRAR.exe"

EXCLUDED = {"aaa0298.com", "aaa1063.com"}

def get_template_name(site_id_str):
    if not DATA_JSON.exists():
        return None
    site_id_int = int(site_id_str)
    with open(DATA_JSON, 'r', encoding='utf-8') as f:
        data = json.load(f)
    for entry in data:
        entry_id = int(entry['id']) if isinstance(entry['id'], str) else entry['id']
        if entry_id == site_id_int:
            name = entry['name']
            match = re.match(r'^k\d+[ _-]', name)
            if match:
                name = name[match.end():]
            return name.strip()
    return None

def compress_with_winrar(source_dir, zip_path, verbose=False):
    if zip_path.exists() and zip_path.stat().st_size > 0:
        if verbose:
            print(f"   ⏭ 壓縮包已存在且非空,跳過")
        return True

    if not os.path.exists(WINRAR_PATH):
        print(f"❌ WinRAR 未找到: {WINRAR_PATH}")
        return False

    # 使用 -afzip 指定 ZIP 格式(比 -t 更兼容)
    cmd = [
        WINRAR_PATH,
        "a",
        "-ep1",                # 排除源目錄前綴
        "-r",                  # 遞歸
        "-afzip",              # 指定 ZIP 格式
        f"-p{PASSWORD}",
        "-ibck",               # 後臺運行
        "-y",
        str(zip_path),
        str(source_dir) + "\\"  # 源目錄路徑
    ]

    if verbose:
        print(f"   執行命令: {' '.join(cmd)}")

    try:
        result = subprocess.run(cmd, capture_output=True, text=True, check=False)
        if verbose:
            print(f"   返回碼: {result.returncode}")
            if result.stdout:
                print(f"   stdout: {result.stdout.strip()}")
            if result.stderr:
                print(f"   stderr: {result.stderr.strip()}")

        if zip_path.exists() and zip_path.stat().st_size > 0:
            return True
        else:
            if verbose:
                print(f"   ❌ 未生成有效文件")
            return False
    except Exception as e:
        if verbose:
            print(f"   ❌ 執行壓縮失敗: {e}")
        return False

def main():
    OUTPUT_DIR.mkdir(parents=True, exist_ok=True)

    site_dirs = []
    for d in WWW_ROOT.glob("aaa*"):
        if not d.is_dir() or d.name in EXCLUDED:
            continue
        if d.name.startswith("aaa") and d.name.endswith(".com"):
            num_part = d.name[3:-4]
            if num_part.isdigit() and len(num_part) >= 4:
                site_dirs.append(d)
    site_dirs.sort(key=lambda x: int(x.name[3:-4]))

    if not site_dirs:
        print("未找到任何站點")
        return

    total = len(site_dirs)
    print(f"📋 共找到 {total} 個站點(已排除 {EXCLUDED})")

    for idx, site_dir in enumerate(site_dirs, 1):
        site_id = site_dir.name[3:-4]
        template_name = get_template_name(site_id)
        if not template_name:
            template_name = f"{site_id}_站點"
        zip_name = f"{site_id}_{template_name}.zip"
        zip_path = OUTPUT_DIR / zip_name

        verbose = (idx <= 3)

        if zip_path.exists() and zip_path.stat().st_size > 0:
            if verbose:
                print(f"\n⏭ {zip_name} 已存在,跳過")
            continue

        print(f"\n📦 [{idx}/{total}] 打包 {site_dir.name} -> {zip_name} ...")
        ok = compress_with_winrar(site_dir, zip_path, verbose)
        if ok:
            print(f"   ✅ 打包成功")
        else:
            print(f"   ❌ 打包失敗")

        if idx == 3:
            print("\n✅ 前3個站點處理完成,請檢查上述日誌。")
            input("按 Enter 鍵繼續處理剩餘站點...")
            print("\n繼續處理剩餘站點(僅輸出簡要信息)...\n")

    print("\n🎉 所有站點打包完成!")

if __name__ == "__main__":
    main()

 

微信赞赏

微信

支付宝赞赏

支付寶

✍️ 作者: 紅穆

網站管理員 · 感謝閱讀,更多精彩內容敬請關注

作者主頁 查看主頁 →

相關文章

Import "requests" could not be resolved from source

Import "requests" could not be resolved from source 語言筆記 python

這個報錯是在使用Pylance這個Python語言服務器時出現的。其中,"Import "requests" could not be resolved from source"這個錯誤提示表示在你的代碼中引用了requests模塊,但是Pylance無法從源中找到該模塊的位置。可能的原因是你沒有安…
👁 2014
重新安装Python和requests库

重新安裝Python和requests庫 語言筆記 python

如果您遇到了 "Import "requests" could not be resolved from source" 的問題,可以嘗試重新安裝 Python 和 requests 庫。首先,您需要卸載當前的 Python 和 requests 庫。在 Windows 系統上,您可以通過在命令提示…
👁 732
WARNING: Skipping requests as it is not installed.

WARNING: Skipping requests as it is not installed. 語言筆記 python

這個錯誤提示說明你的Python環境中缺少requests庫,而你的代碼中又調用了這個庫,因此Python無法正常執行你的代碼。解決這個問題的方法是安裝requests庫。你可以在命令行中使用pip命令來安裝:pip install requests如果你使用的是Python3,可以使用pip3命令…
👁 2383
python报错,这是什么原因?AttributeError: partially initialized module 'openai' has no attribute 'Completion' (most likely due to a circular import)

python報錯,這是什麼原因?AttributeError: partially initialized module 'openai' has no attribute 'Completion' (most likely due to a circular import) 語言筆記 python

這個錯誤提示表明在導入 openai 模塊和特定的 Completion 屬性時出現了問題,很可能是由於循環導入導致的。出現這個錯誤的原因可能是你的代碼中存在兩個或多個模塊之間相互導入,形成了循環依賴。例如,模塊A導入了模塊B,而模塊B又導入了模塊A。循環導入會導致模塊在加載時無法正確地初始化,從而…
👁 936
python如何打包在Windows上运行?

python如何打包在Windows上運行? 語言筆記 python

在Windows上打包和運行Python程序的最常用方式是使用PyInstaller。PyInstaller是一個免費的、跨平臺的Python應用程序打包工具,可以將Python代碼和其依賴的庫打包成一個獨立的可執行文件,使得在沒有安裝Python解釋器的系統上運行Python程序成爲可能。以下是使…
👁 561
python开发用什么编程软件好?

python開發用什麼編程軟件好? 語言筆記 python

Python開發的編程軟件有很多,以下是一些常用的Python集成開發環境(IDE)和編輯器:PyCharmPyCharm是一個由JetBrains開發的集成開發環境,它專爲Python開發者設計。PyCharm功能強大,提供了代碼補全、調試、版本控制、代碼重構等一系列高級功能,可以幫助開發者提高工…
👁 444

推薦閱讀

(自适应手机端)搬家公司搬迁类pbootcms网站模板 家政服务网站源码下载 0353

(自適應手機端)搬家公司搬遷類pbootcms網站模板 家政服務網站源碼下載 0353 實用收藏 pbootcms模板

本套自適應手機端的搬家公司與家政服務PbootCMS網站模板。設計風格熱情高效,適合展示搬家服務、家政保潔及企業形象。有助於搬家公司在線上展示服務,吸引本地及全國客戶。模板展示 安裝說明 網站後臺:/admin.php 賬號:admin 密碼:admin 解壓密碼:www.4s5.cn相關文章Pbo…
👁 273
(自适应手机端)行业协会工会类网站pbootcms模板 机构单位网站源码下载 0617

(自適應手機端)行業協會工會類網站pbootcms模板 機構單位網站源碼下載 0617 實用收藏 pbootcms模板

一款行業協會與工會政府機構PbootCMS網站模板,支持PC與WAP端。設計風格專業穩重,適合行業協會、商會、工會等組織展示職能與活動。有助於公共組織在線上建立官方信息發佈平臺。模板展示 安裝說明 網站後臺:/admin.php 賬號:admin 密碼:admin 解壓密碼:www.4s5.cn相關…
👁 334