搜尋
首頁後端開發Python教學使用 Python 遞歸合併 PDF

Merge PDFs Recursively Using Python

介紹

將多個 PDF 檔案合併到一個文件中可能是一項繁瑣的任務,尤其是當檔案分佈在多個目錄中時。使用 Python,這項任務變得無縫且自動化。在本教學中,我們將使用 PyPDF2 建立一個命令列介面 (CLI) 工具,然後按一下合併目錄(包括其子目錄)中的所有 PDF 文件,同時排除 .venv 和 .git 等特定目錄。


先決條件

開始之前,請確保您具備以下條件:

  1. Python:版本 3.7 或更高版本。
  2. pip:Python 的套件管理器。
  3. 所需的庫

    • 安裝 PyPDF2 進行 PDF 操作:
     pip install PyPDF2
    
  • 安裝點擊以建立 CLI:

     pip install click
    

代碼演練

這是我們的 CLI 工具的完整程式碼:

import click
from pathlib import Path
from PyPDF2 import PdfMerger
import os

EXCLUDED_DIRS = {".venv", ".git"}

@click.command()
@click.argument("directory", type=click.Path(exists=True, file_okay=False, path_type=Path))
@click.argument("output_file", type=click.Path(dir_okay=False, writable=True, path_type=Path))
def merge_pdfs(directory: Path, output_file: Path):
    """
    Merge all PDF files from DIRECTORY and its subdirectories into OUTPUT_FILE,
    excluding specified directories like .venv and .git.
    """
    # Initialize the PdfMerger
    merger = PdfMerger()

    # Walk through the directory tree, including the base directory
    for root, dirs, files in os.walk(directory):
        # Exclude specific directories
        dirs[:] = [d for d in dirs if d not in EXCLUDED_DIRS]

        # Convert the root to a Path object
        current_dir = Path(root)

        click.echo(f"Processing directory: {current_dir}")

        # Collect PDF files in the current directory
        pdf_files = sorted(current_dir.glob("*.pdf"))

        if not pdf_files:
            click.echo(f"No PDF files found in {current_dir}")
            continue

        # Add PDF files from the current directory
        for pdf in pdf_files:
            click.echo(f"Adding {pdf}...")
            merger.append(str(pdf))

    # Write the merged output file
    output_file.parent.mkdir(parents=True, exist_ok=True)
    merger.write(str(output_file))
    merger.close()

    click.echo(f"All PDFs merged into {output_file}")

if __name__ == "__main__":
    merge_pdfs()

它是如何運作的

  1. 目錄遍歷:

    • os.walk()函數遞歸遍歷指定目錄。
    • 使用目錄過濾器排除特定目錄(例如 .venv、.git)。
  2. PDF 文件集合:

    • current_dir.glob("*.pdf") 收集目前目錄下的所有 PDF 檔案。
  3. 合併 PDF:

    • PyPDF2 中的 PdfMerger 用於附加所有 PDF。
    • 合併後的輸出寫入指定檔。
  4. CLI 整合:

    • 點選庫可以輕鬆提供目錄和輸出檔案路徑作為參數。

運行工具

將程式碼儲存到檔案中,例如 merge_pdfs.py。從終端運行它,如下所示:

python merge_pdfs.py /path/to/directory /path/to/output.pdf

例子

假設您有以下目錄結構:

/documents
├── file1.pdf
├── subdir1
│   ├── file2.pdf
├── subdir2
│   ├── file3.pdf
├── .git
│   ├── ignored_file.pdf

如下運行該工具:

python merge_pdfs.py /documents /merged.pdf

這會將 file1.pdf、file2.pdf 和 file3.pdf 合併為 merged.pdf,跳過 .git。


特徵

  1. 遞歸合併:

    • 工具會自動包含所有子目錄中的 PDF。
  2. 目錄排除:

    • 排除 .venv 和 .git 等目錄以避免不相關的檔案。
  3. 排序合併:

    • 確保 PDF 按排序順序新增以獲得一致的結果。
  4. CLI 簡單性:

    • 提供使用者直覺的介面來指定輸入和輸出路徑。

注意事項和限制

  1. 大檔案

    • 合併大量 PDF 可能會消耗大量記憶體。首先使用較小的資料集進行測試。
  2. PDF 相容性:

    • 確保所有輸入的 PDF 有效且未損壞。
  3. 自訂排除

    • 修改 EXCLUDED_DIRS 設定以根據需要排除其他目錄。

結論

本教學示範如何使用 Python 自動合併目錄結構中的 PDF。提供的 CLI 工具非常靈活,可以適應更複雜的工作流程。嘗試一下,讓我們知道它如何為您服務!

編碼愉快! ?

以上是使用 Python 遞歸合併 PDF的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Python:編譯器還是解釋器?Python:編譯器還是解釋器?May 13, 2025 am 12:10 AM

Python是解釋型語言,但也包含編譯過程。 1)Python代碼先編譯成字節碼。 2)字節碼由Python虛擬機解釋執行。 3)這種混合機制使Python既靈活又高效,但執行速度不如完全編譯型語言。

python用於循環與循環時:何時使用哪個?python用於循環與循環時:何時使用哪個?May 13, 2025 am 12:07 AM

UseeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.forloopsareIdealForkNownsences,而WhileLeleLeleLeleLeleLoopSituationSituationsItuationsItuationSuationSituationswithUndEtermentersitations。

Python循環:最常見的錯誤Python循環:最常見的錯誤May 13, 2025 am 12:07 AM

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐個偏置,零indexingissues,andnestedloopineflinefficiencies

對於循環和python中的循環時:每個循環的優點是什麼?對於循環和python中的循環時:每個循環的優點是什麼?May 13, 2025 am 12:01 AM

forloopsareadvantageousforknowniterations and sequests,供應模擬性和可讀性;而LileLoopSareIdealFordyNamicConcitionSandunknowniterations,提供ControloperRoverTermination.1)forloopsareperfectForeTectForeTerToratingOrtratingRiteratingOrtratingRitterlistlistslists,callings conspass,calplace,cal,ofstrings ofstrings,orstrings,orstrings,orstrings ofcces

Python:深入研究彙編和解釋Python:深入研究彙編和解釋May 12, 2025 am 12:14 AM

pythonisehybridmodeLofCompilation和interpretation:1)thepythoninterpretercompilesourcecececodeintoplatform- interpententbybytecode.2)thepythonvirtualmachine(pvm)thenexecutecutestestestestestesthisbytecode,ballancingEaseofuseEfuseWithPerformance。

Python是一種解釋或編譯語言,為什麼重要?Python是一種解釋或編譯語言,為什麼重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允許fordingfordforderynamictynamictymictymictymictyandrapiddefupment,儘管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

對於python中的循環時循環與循環:解釋了關鍵差異對於python中的循環時循環與循環:解釋了關鍵差異May 12, 2025 am 12:08 AM

在您的知識之際,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations則youneedtoloopuntilaconditionismet

循環時:實用指南循環時:實用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具