最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python自動化辦公的10個腳本合集(含源碼)

 更新時間:2025年11月12日 09:09:11   作者:小莊-Python辦公  
這篇文章主要為大家詳細介紹了Python自動化辦公的10個腳本合集,這些腳本覆蓋郵件、Excel處理、圖片、PDF和歸檔等常見辦公場景,大家可以根據(jù)需要進行選擇

前言

這些腳本覆蓋郵件、Excel處理、圖片、PDF和歸檔等常見辦公場景,并在本文中完整嵌入源碼,便于復制與學習。

1. 批量文件重命名 (bulk_rename.py)

批量文件重命名

用途:為目錄內(nèi)的文件批量添加前綴/后綴、序號,或進行字符串替換。

命令行用法:

python bulk_rename.py --dir “./docs” --prefix “NEW_” --suffix “_v2” --start 1 --pad 3 --replace “old:new” --ext “.pdf” --dry-run

示例:python bulk_rename.py --dir “./images” --prefix “IMG_” --start 1 --pad 4

源碼

"""
批量文件重命名

用途:為目錄內(nèi)的文件批量添加前綴/后綴、序號,或進行字符串替換。

命令行用法:
  python bulk_rename.py --dir "./docs" --prefix "NEW_" --suffix "_v2" \
    --start 1 --pad 3 --replace "old:new" --ext ".pdf" --dry-run

示例:
  python bulk_rename.py --dir "./images" --prefix "IMG_" --start 1 --pad 4
"""

import argparse
from pathlib import Path


def plan_new_name(path: Path, prefix: str, suffix: str, seq: int | None, pad: int, replace: str | None) -> Path:
    base = path.stem
    if replace:
        if ":" in replace:
            old, new = replace.split(":", 1)
        else:
            old, new = replace, ""
        base = base.replace(old, new)

    new_base = f"{prefix}{base}{suffix}"
    if seq is not None:
        new_base = f"{new_base}_{str(seq).zfill(pad)}"
    return path.with_name(new_base + path.suffix)


def main():
    parser = argparse.ArgumentParser(description="批量文件重命名")
    parser.add_argument("--dir", required=True, help="目標目錄")
    parser.add_argument("--prefix", default="", help="添加到文件名開頭的前綴")
    parser.add_argument("--suffix", default="", help="添加到文件名末尾的后綴")
    parser.add_argument("--start", type=int, help="序號起始值,例如1")
    parser.add_argument("--pad", type=int, default=3, help="序號補零位數(shù),如3生成001")
    parser.add_argument("--replace", help="字符串替換,格式 old:new 或僅提供old刪除之")
    parser.add_argument("--ext", help="僅處理指定擴展名,如 .pdf 或 .jpg")
    parser.add_argument("--dry-run", action="store_true", help="只預覽重命名方案,不實際執(zhí)行")

    args = parser.parse_args()

    root = Path(args.dir)
    if not root.exists() or not root.is_dir():
        raise SystemExit("目錄不存在或不是目錄")

    files = [p for p in sorted(root.iterdir()) if p.is_file()]
    if args.ext:
        files = [p for p in files if p.suffix.lower() == args.ext.lower()]

    seq = args.start
    for i, f in enumerate(files):
        current_seq = (seq + i) if seq is not None else None
        new_path = plan_new_name(f, args.prefix, args.suffix, current_seq, args.pad, args.replace)
        if args.dry_run:
            print(f"預覽: {f.name} -> {new_path.name}")
        else:
            f.rename(new_path)
            print(f"重命名: {f.name} -> {new_path.name}")


if __name__ == "__main__":
    main()

2. CSV轉(zhuǎn)Excel (csv_to_excel.py)

CSV轉(zhuǎn)Excel

用途:將CSV文件轉(zhuǎn)換為Excel(支持指定工作表名)。

命令行用法:

python csv_to_excel.py --input “data.csv” --output “data.xlsx” --sheet-name “Sheet1”

示例:python csv_to_excel.py --input “report.csv” --output “report.xlsx”

源碼

"""
CSV轉(zhuǎn)Excel

用途:將CSV文件轉(zhuǎn)換為Excel(支持指定工作表名)。

命令行用法:
  python csv_to_excel.py --input "data.csv" --output "data.xlsx" --sheet-name "Sheet1"

示例:
  python csv_to_excel.py --input "report.csv" --output "report.xlsx"
"""

import argparse
from pathlib import Path
import pandas as pd


def main():
    parser = argparse.ArgumentParser(description="CSV轉(zhuǎn)Excel")
    parser.add_argument("--input", required=True, help="輸入CSV文件")
    parser.add_argument("--output", required=True, help="輸出Excel文件")
    parser.add_argument("--sheet-name", default="Sheet1", help="工作表名")

    args = parser.parse_args()

    df = pd.read_csv(args.input, encoding="utf-8-sig")
    df.to_excel(args.output, index=False)
    print(f"已生成: {args.output} (sheet: {args.sheet_name})")


if __name__ == "__main__":
    main()

3. Excel按列去重 (excel_deduplicate.py)

Excel按列去重

用途:按指定關(guān)鍵列對Excel數(shù)據(jù)去重,并輸出新的Excel文件。

命令行用法:

python excel_deduplicate.py --input data.xlsx --output dedup.xlsx --key-columns “郵箱,姓名”

示例:python excel_deduplicate.py --input data.xlsx --key-columns “ID”

源碼

"""
Excel按列去重

用途:按指定關(guān)鍵列對Excel數(shù)據(jù)去重,并輸出新的Excel文件。

命令行用法:
  python excel_deduplicate.py --input data.xlsx --output dedup.xlsx --key-columns "郵箱,姓名"

示例:
  python excel_deduplicate.py --input data.xlsx --key-columns "ID"
"""

import argparse
import pandas as pd


def parse_keys(text: str | None) -> list[str]:
    if not text:
        return []
    return [k.strip() for k in text.split(",") if k.strip()]


def main():
    parser = argparse.ArgumentParser(description="Excel按列去重")
    parser.add_argument("--input", required=True, help="輸入Excel文件")
    parser.add_argument("--output", default="dedup.xlsx", help="輸出Excel文件")
    parser.add_argument("--key-columns", required=True, help="關(guān)鍵列,逗號分隔")

    args = parser.parse_args()

    keys = parse_keys(args.key_columns)
    if not keys:
        raise SystemExit("請?zhí)峁┲辽僖粋€關(guān)鍵列 --key-columns")

    df = pd.read_excel(args.input)
    dedup = df.drop_duplicates(subset=keys)
    dedup.to_excel(args.output, index=False)
    print(f"去重完成: {args.output} (由{len(df)}行 -> {len(dedup)}行)")


if __name__ == "__main__":
    main()

4. 合并多個Excel文件到一個工作表 (excel_merge_files.py)

合并多個Excel文件到一個工作表

用途:批量讀取目錄下的Excel文件并合并為一個Excel;可選增加來源文件名列。

命令行用法:

python excel_merge_files.py --input-dir ./excels --pattern “*.xlsx” --output merged.xlsx --sheet-name merged --add-source-col

示例:python excel_merge_files.py --input-dir ./data --output all.xlsx --add-source-col

源碼

"""
合并多個Excel文件到一個工作表

用途:批量讀取目錄下的Excel文件并合并為一個Excel;可選增加來源文件名列。

命令行用法:
  python excel_merge_files.py --input-dir ./excels --pattern "*.xlsx" \
    --output merged.xlsx --sheet-name merged --add-source-col

示例:
  python excel_merge_files.py --input-dir ./data --output all.xlsx --add-source-col
"""

import argparse
from pathlib import Path
import pandas as pd


def main():
    parser = argparse.ArgumentParser(description="合并目錄中的多個Excel文件到一個")
    parser.add_argument("--input-dir", required=True, help="包含Excel的目錄")
    parser.add_argument("--pattern", default="*.xlsx", help="文件匹配模式(默認*.xlsx)")
    parser.add_argument("--output", default="merged.xlsx", help="輸出Excel文件名")
    parser.add_argument("--sheet-name", default="merged", help="輸出工作表名")
    parser.add_argument("--add-source-col", action="store_true", help="增加來源文件名列")

    args = parser.parse_args()

    root = Path(args.input_dir)
    files = sorted(root.glob(args.pattern))
    if not files:
        raise SystemExit("未找到Excel文件")

    frames = []
    for f in files:
        df = pd.read_excel(f)
        if args.add_source_col:
            df["源文件"] = f.name
        frames.append(df)

    merged = pd.concat(frames, ignore_index=True)
    merged.to_excel(args.output, index=False)
    print(f"合并完成: {args.output} (共{len(files)}個文件, {len(merged)}行)")


if __name__ == "__main__":
    main()

5. Excel按列拆分 (excel_split_columns.py)

Excel按列拆分

用途:將每一列單獨導出為獨立文件(xlsx或csv)。

命令行用法:

python excel_split_columns.py --input “data.xlsx” --sheet “Sheet1” --output-dir “./out_cols” --to “xlsx”

示例:python excel_split_columns.py --input “data.xlsx” --to “csv”

源碼

"""
Excel按列拆分

用途:將每一列單獨導出為獨立文件(xlsx或csv)。

命令行用法:
  python excel_split_columns.py --input "data.xlsx" --sheet "Sheet1" \
    --output-dir "./out_cols" --to "xlsx"

示例:
  python excel_split_columns.py --input "data.xlsx" --to "csv"
"""

import argparse
from pathlib import Path
import pandas as pd


def main():
    parser = argparse.ArgumentParser(description="按列拆分Excel為多個文件")
    parser.add_argument("--input", required=True, help="輸入Excel文件")
    parser.add_argument("--sheet", help="工作表名稱")
    parser.add_argument("--output-dir", default="out_cols", help="輸出目錄")
    parser.add_argument("--to", choices=["xlsx", "csv"], default="xlsx", help="導出格式")

    args = parser.parse_args()

    out_dir = Path(args.output_dir)
    out_dir.mkdir(parents=True, exist_ok=True)

    df = pd.read_excel(args.input, sheet_name=args.sheet)
    for col in df.columns:
        col_df = df[[col]]
        safe = "".join(c if c not in "/\\:*?\"<>|" else "_" for c in str(col))
        if args.to == "csv":
            out_path = out_dir / f"col_{safe}.csv"
            col_df.to_csv(out_path, index=False, encoding="utf-8-sig")
        else:
            out_path = out_dir / f"col_{safe}.xlsx"
            col_df.to_excel(out_path, index=False)
        print(f"導出: {out_path}")


if __name__ == "__main__":
    main()

6. Excel按行拆分(按列分組導出) (excel_split_rows.py)

Excel按行拆分(按列分組導出)

用途:按某一列的唯一值,將Excel工作表拆分為多個文件;未提供分組列時按每行導出一個文件。

命令行用法:

python excel_split_rows.py --input “data.xlsx” --sheet “Sheet1” --key-column “部門” --output-dir “./out”

示例:python excel_split_rows.py --input “data.xlsx” --key-column “部門”

源碼

"""
Excel按行拆分(按列分組導出)

用途:按某一列的唯一值,將Excel工作表拆分為多個文件;未提供分組列時按每行導出一個文件。

命令行用法:
  python excel_split_rows.py --input "data.xlsx" --sheet "Sheet1" \
    --key-column "部門" --output-dir "./out"

示例:
  python excel_split_rows.py --input "data.xlsx" --key-column "部門"
"""

import argparse
from pathlib import Path
import pandas as pd


def sanitize_filename(name: str) -> str:
    return "".join(c if c not in "/\\:*?\"<>|" else "_" for c in str(name)).strip()


def main():
    parser = argparse.ArgumentParser(description="按列分組或按行將Excel拆分為多個文件")
    parser.add_argument("--input", required=True, help="輸入Excel文件路徑")
    parser.add_argument("--sheet", help="工作表名稱,默認首個工作表")
    parser.add_argument("--key-column", help="分組列名,按此列的唯一值拆分")
    parser.add_argument("--output-dir", default="out_rows", help="輸出目錄")

    args = parser.parse_args()

    out_dir = Path(args.output_dir)
    out_dir.mkdir(parents=True, exist_ok=True)

    df = pd.read_excel(args.input, sheet_name=args.sheet)

    if args.key_column and args.key_column in df.columns:
        for key, group in df.groupby(args.key_column):
            fname = sanitize_filename(key)
            out_path = out_dir / f"{fname}.xlsx"
            group.to_excel(out_path, index=False)
            print(f"導出: {out_path}")
    else:
        for i in range(len(df)):
            row_df = df.iloc[[i]]
            out_path = out_dir / f"row_{i+1}.xlsx"
            row_df.to_excel(out_path, index=False)
            print(f"導出: {out_path}")


if __name__ == "__main__":
    main()

7. 文件夾打包為ZIP (folder_backup_zip.py)

文件夾打包為ZIP

用途:將指定目錄打包為ZIP,支持排除某些通配模式的文件。

命令行用法:

python folder_backup_zip.py --source-dir ./project --output backup.zip --exclude “.tmp,.log”

示例:python folder_backup_zip.py --source-dir ./docs --output docs.zip

源碼

"""
文件夾打包為ZIP

用途:將指定目錄打包為ZIP,支持排除某些通配模式的文件。

命令行用法:
  python folder_backup_zip.py --source-dir ./project --output backup.zip --exclude "*.tmp,*.log"

示例:
  python folder_backup_zip.py --source-dir ./docs --output docs.zip
"""

import argparse
import fnmatch
import os
from pathlib import Path
import zipfile


def parse_patterns(text: str | None) -> list[str]:
    if not text:
        return []
    return [p.strip() for p in text.split(",") if p.strip()]


def should_exclude(name: str, patterns: list[str]) -> bool:
    return any(fnmatch.fnmatch(name, pat) for pat in patterns)


def main():
    parser = argparse.ArgumentParser(description="文件夾打包為ZIP")
    parser.add_argument("--source-dir", required=True, help="源目錄")
    parser.add_argument("--output", default="backup.zip", help="輸出ZIP文件名")
    parser.add_argument("--exclude", help="排除模式,逗號分隔,如 *.tmp,*.log")
    parser.add_argument("--store-absolute", action="store_true", help="在ZIP內(nèi)保存絕對路徑(默認保存相對路徑)")

    args = parser.parse_args()

    src = Path(args.source_dir)
    if not src.exists() or not src.is_dir():
        raise SystemExit("源目錄不存在")

    patterns = parse_patterns(args.exclude)

    with zipfile.ZipFile(args.output, "w", compression=zipfile.ZIP_DEFLATED) as zf:
        for root, _, files in os.walk(src):
            for name in files:
                full = Path(root) / name
                rel = full if args.store_absolute else full.relative_to(src)
                if should_exclude(name, patterns):
                    continue
                zf.write(full, arcname=str(rel))
                print(f"添加: {rel}")

    print(f"打包完成: {args.output}")


if __name__ == "__main__":
    main()

8. 批量圖片改尺寸 (image_resize_batch.py)

批量圖片改尺寸

用途:批量將圖片按指定尺寸縮放,支持保持寬高比與輸出質(zhì)量。

命令行用法:

python image_resize_batch.py --input-dir “./images” --output-dir “./resized” --width 1024 --height 768 --keep-aspect --quality 85

示例:python image_resize_batch.py --input-dir ./imgs --output-dir ./out --width 1080 --keep-aspect

源碼

"""
批量圖片改尺寸

用途:批量將圖片按指定尺寸縮放,支持保持寬高比與輸出質(zhì)量。

命令行用法:
  python image_resize_batch.py --input-dir "./images" --output-dir "./resized" \
    --width 1024 --height 768 --keep-aspect --quality 85

示例:
  python image_resize_batch.py --input-dir ./imgs --output-dir ./out --width 1080 --keep-aspect
"""

import argparse
from pathlib import Path
from PIL import Image


SUPPORTED_EXTS = {".jpg", ".jpeg", ".png", ".bmp", ".tif", ".tiff", ".webp"}


def calc_size(orig_w: int, orig_h: int, width: int | None, height: int | None, keep_aspect: bool) -> tuple[int, int]:
    if not keep_aspect:
        return width or orig_w, height or orig_h
    # 保持比例:按給定邊界等比縮放
    if width and height:
        r = min(width / orig_w, height / orig_h)
        return max(1, int(orig_w * r)), max(1, int(orig_h * r))
    if width and not height:
        r = width / orig_w
        return max(1, int(orig_w * r)), max(1, int(orig_h * r))
    if height and not width:
        r = height / orig_h
        return max(1, int(orig_w * r)), max(1, int(orig_h * r))
    return orig_w, orig_h


def main():
    parser = argparse.ArgumentParser(description="批量圖片改尺寸")
    parser.add_argument("--input-dir", required=True, help="輸入圖片目錄")
    parser.add_argument("--output-dir", default="resized", help="輸出目錄")
    parser.add_argument("--width", type=int, help="目標寬度")
    parser.add_argument("--height", type=int, help="目標高度")
    parser.add_argument("--keep-aspect", action="store_true", help="保持寬高比")
    parser.add_argument("--quality", type=int, default=85, help="JPEG質(zhì)量(1-95)")

    args = parser.parse_args()

    in_dir = Path(args.input_dir)
    out_dir = Path(args.output_dir)
    out_dir.mkdir(parents=True, exist_ok=True)

    for p in sorted(in_dir.iterdir()):
        if not p.is_file() or p.suffix.lower() not in SUPPORTED_EXTS:
            continue
        img = Image.open(p)
        new_w, new_h = calc_size(img.width, img.height, args.width, args.height, args.keep_aspect)
        resized = img.resize((new_w, new_h), Image.LANCZOS)
        out_path = out_dir / p.name
        save_kwargs = {}
        if out_path.suffix.lower() in {".jpg", ".jpeg"}:
            save_kwargs["quality"] = args.quality
            save_kwargs["optimize"] = True
        resized.save(out_path, **save_kwargs)
        print(f"導出: {out_path} ({img.width}x{img.height} -> {new_w}x{new_h})")


if __name__ == "__main__":
    main()

9. 批量PDF合并 (pdf_merge.py)

批量PDF合并

用途:將目錄中的多個PDF文件按名稱排序合并為一個PDF。

命令行用法:

python pdf_merge.py --input-dir ./pdfs --pattern “*.pdf” --output merged.pdf

示例:python pdf_merge.py --input-dir ./pdfs --output all.pdf

源碼

"""
批量PDF合并

用途:將目錄中的多個PDF文件按名稱排序合并為一個PDF。

命令行用法:
  python pdf_merge.py --input-dir ./pdfs --pattern "*.pdf" --output merged.pdf

示例:
  python pdf_merge.py --input-dir ./pdfs --output all.pdf
"""

import argparse
from pathlib import Path
from pypdf import PdfWriter, PdfReader


def main():
    parser = argparse.ArgumentParser(description="批量PDF合并")
    parser.add_argument("--input-dir", required=True, help="PDF所在目錄")
    parser.add_argument("--pattern", default="*.pdf", help="文件匹配模式(默認*.pdf)")
    parser.add_argument("--output", default="merged.pdf", help="輸出PDF文件名")

    args = parser.parse_args()

    root = Path(args.input_dir)
    files = sorted(root.glob(args.pattern))
    if not files:
        raise SystemExit("未找到PDF文件")

    writer = PdfWriter()
    for f in files:
        reader = PdfReader(f)
        for page in reader.pages:
            writer.add_page(page)
        print(f"合并: {f.name}")

    with open(args.output, "wb") as out:
        writer.write(out)
    print(f"完成: {args.output}")


if __name__ == "__main__":
    main()

10. 自動發(fā)郵件 (send_email.py)

自動發(fā)郵件

用途:通過 SMTP 發(fā)送郵件,支持多個收件人、抄送、附件目錄;可選從環(huán)境變量/.env讀取配置。

依賴:標準庫(smtplib、email、ssl、mimetypes),可選 python-dotenv。

命令行用法:

python send_email.py --smtp-server smtp.example.com --port 465 --username user@example.com --password your_password --to “a@x.com,b@y.com” --subject “主題” --body-file “body.md” --attachments-dir “./attachments”

示例:python send_email.py --use-env --to “boss@company.com” --subject “周報” --body “本周進展見附件” --attachments-dir “./out”

源碼

"""
自動發(fā)郵件

用途:通過 SMTP 發(fā)送郵件,支持多個收件人、抄送、附件目錄;可選從環(huán)境變量/.env讀取配置。
依賴:標準庫(smtplib、email、ssl、mimetypes),可選 python-dotenv。

命令行用法:
  python send_email.py --smtp-server smtp.example.com --port 465 \
    --username user@example.com --password your_password \
    --to "a@x.com,b@y.com" --subject "主題" --body-file "body.md" \
    --attachments-dir "./attachments"

示例:
  python send_email.py --use-env --to "boss@company.com" --subject "周報" \
    --body "本周進展見附件" --attachments-dir "./out"
"""

import argparse
import mimetypes
import os
import ssl
from email.message import EmailMessage
from pathlib import Path
import smtplib

try:
    from dotenv import load_dotenv  # type: ignore
except Exception:
    load_dotenv = None


def parse_list(text: str | None) -> list[str]:
    if not text:
        return []
    return [x.strip() for x in text.split(",") if x.strip()]


def read_body(body: str | None, body_file: str | None) -> str:
    if body_file:
        return Path(body_file).read_text(encoding="utf-8")
    return body or ""


def collect_attachments(dir_path: str | None) -> list[Path]:
    if not dir_path:
        return []
    p = Path(dir_path)
    if not p.exists() or not p.is_dir():
        return []
    return [f for f in sorted(p.iterdir()) if f.is_file()]


def build_message(sender: str, to: list[str], cc: list[str], subject: str, body: str, html: bool,
                  attachments: list[Path]) -> EmailMessage:
    msg = EmailMessage()
    msg["From"] = sender
    msg["To"] = ", ".join(to)
    if cc:
        msg["Cc"] = ", ".join(cc)
    msg["Subject"] = subject

    if html:
        msg.add_alternative(body, subtype="html")
    else:
        msg.set_content(body)

    for path in attachments:
        ctype, encoding = mimetypes.guess_type(path.name)
        if ctype is None or encoding is not None:
            ctype = "application/octet-stream"
        maintype, subtype = ctype.split("/", 1)
        with open(path, "rb") as f:
            msg.add_attachment(f.read(), maintype=maintype, subtype=subtype, filename=path.name)

    return msg


def send_email(
    smtp_server: str,
    port: int,
    username: str,
    password: str,
    sender: str,
    to: list[str],
    cc: list[str],
    bcc: list[str],
    subject: str,
    body: str,
    html: bool,
    attachments: list[Path],
) -> None:
    # 構(gòu)建并發(fā)送郵件
    message = build_message(sender, to, cc, subject, body, html, attachments)

    all_rcpts = list({*(to or []), *(cc or []), *(bcc or [])})
    context = ssl.create_default_context()

    # 465默認走SSL,其他端口嘗試StartTLS
    if port == 465:
        with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
            server.login(username, password)
            server.send_message(message, from_addr=sender, to_addrs=all_rcpts)
    else:
        with smtplib.SMTP(smtp_server, port) as server:
            server.ehlo()
            try:
                server.starttls(context=context)
                server.ehlo()
            except smtplib.SMTPException:
                pass
            server.login(username, password)
            server.send_message(message, from_addr=sender, to_addrs=all_rcpts)


def main():
    parser = argparse.ArgumentParser(description="通過SMTP發(fā)送郵件,支持附件、抄送、HTML正文")
    parser.add_argument("--smtp-server", help="SMTP服務(wù)器地址")
    parser.add_argument("--port", type=int, default=465, help="SMTP端口,默認465(SSL)")
    parser.add_argument("--username", help="SMTP用戶名")
    parser.add_argument("--password", help="SMTP密碼/授權(quán)碼")
    parser.add_argument("--from", dest="sender", help="發(fā)件人地址(默認同用戶名)")
    parser.add_argument("--to", required=True, help="收件人列表,逗號分隔")
    parser.add_argument("--cc", help="抄送列表,逗號分隔")
    parser.add_argument("--bcc", help="密送列表,逗號分隔")
    parser.add_argument("--subject", default="(無主題)", help="郵件主題")
    parser.add_argument("--body", help="純文本正文")
    parser.add_argument("--body-file", help="從文件讀取正文")
    parser.add_argument("--html", action="store_true", help="將正文按HTML發(fā)送")
    parser.add_argument("--attachments-dir", help="附件目錄,將目錄下所有文件作為附件")
    parser.add_argument("--use-env", action="store_true", help="從環(huán)境變量/.env讀取SMTP配置")

    args = parser.parse_args()

    if args.use_env and load_dotenv:
        # 允許使用本地 .env 文件
        if Path(".env").exists():
            load_dotenv(".env")
        else:
            load_dotenv()

    smtp_server = args.smtp_server or os.getenv("SMTP_SERVER") or ""
    port = args.port or int(os.getenv("SMTP_PORT", "465"))
    username = args.username or os.getenv("SMTP_USER") or ""
    password = args.password or os.getenv("SMTP_PASS") or ""

    if not smtp_server or not username or not password:
        raise SystemExit("缺少SMTP配置:請?zhí)峁?--smtp-server/--username/--password 或使用 --use-env 并設(shè)置環(huán)境變量")

    sender = args.sender or username
    to = parse_list(args.to)
    cc = parse_list(args.cc)
    bcc = parse_list(args.bcc)
    body = read_body(args.body, args.body_file)
    attachments = collect_attachments(args.attachments_dir)

    if not to:
        raise SystemExit("至少需要一個收件人 --to")

    send_email(
        smtp_server=smtp_server,
        port=port,
        username=username,
        password=password,
        sender=sender,
        to=to,
        cc=cc,
        bcc=bcc,
        subject=args.subject,
        body=body,
        html=args.html,
        attachments=attachments,
    )


if __name__ == "__main__":
    main()

以上就是Python自動化辦公的10個腳本合集(含源碼)的詳細內(nèi)容,更多關(guān)于Python自動化辦公腳本的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Python調(diào)整PDF頁面尺寸大小的兩種方法

    Python調(diào)整PDF頁面尺寸大小的兩種方法

    利用Python語言的高效性和靈活性,再結(jié)合Spire.PDF for Python 庫的強大功能,我們可以通過Python代碼輕松實現(xiàn)對PDF頁面的批量調(diào)整,在這篇文章中,我們將介紹兩種調(diào)整PDF頁面大小的方法,感興趣的朋友可以參考下
    2024-05-05
  • python制作websocket服務(wù)器實例分享

    python制作websocket服務(wù)器實例分享

    websocket是一個瀏覽器和服務(wù)器通信的新的協(xié)議,websocket則和一般的socket一樣,使得瀏覽器和服務(wù)器建立了一個雙工的通道。今天我們就來詳細探討下使用Python實現(xiàn)websocket服務(wù)器的具體方法
    2016-11-11
  • 使用Python實現(xiàn)簡單的學生成績管理系統(tǒng)

    使用Python實現(xiàn)簡單的學生成績管理系統(tǒng)

    這篇文章主要為大家詳細介紹了Python實現(xiàn)學生成績管理系統(tǒng),使用數(shù)據(jù)庫,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-01-01
  • 樹莓派使用USB攝像頭和motion實現(xiàn)監(jiān)控

    樹莓派使用USB攝像頭和motion實現(xiàn)監(jiān)控

    這篇文章主要為大家詳細介紹了樹莓派使用USB攝像頭和motion實現(xiàn)監(jiān)控,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-06-06
  • Python常用模塊之requests模塊用法分析

    Python常用模塊之requests模塊用法分析

    這篇文章主要介紹了Python常用模塊之requests模塊用法,結(jié)合實例形式分析了Python使用requests模塊發(fā)送GET、POST請求及響應(yīng)相關(guān)操作技巧,需要的朋友可以參考下
    2019-05-05
  • Python中防止sql注入的方法詳解

    Python中防止sql注入的方法詳解

    SQL注入是比較常見的網(wǎng)絡(luò)攻擊方式之一,它不是利用操作系統(tǒng)的BUG來實現(xiàn)攻擊,而是針對程序員編程時的疏忽,通過SQL語句,實現(xiàn)無帳號登錄,甚至篡改數(shù)據(jù)庫。下面這篇文章主要給大家介紹了關(guān)于Python中防止sql注入的方法,需要的朋友可以參考下。
    2017-02-02
  • Python編寫一個Excel批量處理的桌面實用腳本

    Python編寫一個Excel批量處理的桌面實用腳本

    在辦公自動化的需求越來越多的今天,用 Python 做一個屬于自己的“批處理小工具”,能輕松幫你節(jié)省大量重復勞動,下面我們就來看看如何使用Python編寫一個Excel批量處理的桌面實用腳本吧
    2025-11-11
  • 詳解Python中DOM方法的動態(tài)性

    詳解Python中DOM方法的動態(tài)性

    這篇文章主要介紹了詳解Python中DOM方法的動態(tài)性,xml.dom模塊在Python的網(wǎng)絡(luò)編程中相當有用,本文來自于IBM官網(wǎng)的開發(fā)者技術(shù)文檔,需要的朋友可以參考下
    2015-04-04
  • python中文件導入的使用(在同一目錄下和在不同目錄下)

    python中文件導入的使用(在同一目錄下和在不同目錄下)

    在Python中,使用pathlib模塊的Path類可以方便地導入不同目錄下的文件,本文就來介紹一下,需要的朋友們下面隨著小編來一起學習學習吧
    2024-12-12
  • python RSA加密的示例

    python RSA加密的示例

    這篇文章主要介紹了python RSA加密的示例,幫助大家更好的理解和使用加密算法,感興趣的朋友可以了解下
    2020-12-12

最新評論

南京市| 樟树市| 烟台市| 麻江县| 彭州市| 海阳市| 方正县| 凤阳县| 曲松县| 平遥县| 香港| 普定县| 茌平县| 资阳市| 城步| 鹤庆县| 汽车| 阳东县| 天全县| 通化县| 自贡市| 隆尧县| 惠水县| 安远县| 新河县| 延安市| 安义县| 门头沟区| 安仁县| 湟中县| 双鸭山市| 宿松县| 临高县| 姚安县| 新晃| 延津县| 河北省| 阿城市| 河南省| 浮山县| 淳安县|