導入
複数の PDF ファイルを 1 つのドキュメントに結合することは、特にファイルが複数のディレクトリにまたがっている場合には、面倒な作業になる可能性があります。 Python を使用すると、このタスクがシームレスかつ自動化されます。このチュートリアルでは、PyPDF2 を使用してコマンド ライン インターフェイス (CLI) ツールを作成し、.venv や .git などの特定のディレクトリを除外しながら、ディレクトリ (そのサブディレクトリを含む) 内のすべての PDF ファイルをクリックして結合します。
前提条件
始める前に、以下のものがあることを確認してください:
- Python: バージョン 3.7 以降。
- pip: Python のパッケージマネージャー。
-
必要なライブラリ:
- PDF 操作のために PyPDF2 をインストールします。
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()
仕組み
-
ディレクトリトラバーサル:
- os.walk() 関数は、指定されたディレクトリを再帰的に走査します。
- 特定のディレクトリ (.venv、.git など) は、ディレクトリのフィルターを使用して除外されます。
-
PDF ファイルコレクション:
- current_dir.glob("*.pdf") は、現在のディレクトリ内のすべての PDF ファイルを収集します。
-
PDF の結合:
- PyPDF2 の PdfMerger は、すべての PDF を追加するために使用されます。
- マージされた出力は、指定されたファイルに書き込まれます。
-
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 が .git をスキップして、merged.pdf にマージされます。
特徴
-
再帰的マージ:
- このツールには、すべてのサブディレクトリの PDF が自動的に組み込まれます。
-
ディレクトリの除外:
- 無関係なファイルを避けるために、.venv や .git などのディレクトリを除外します。
-
ソートされたマージ:
- 一貫した結果を得るために、PDF がソートされた順序で追加されるようにします。
-
CLI シンプルさ:
- ユーザーが入力パスと出力パスを指定するための直感的なインターフェイスを提供します。
注意事項と制限事項
-
大きなファイル:
- 多数の PDF を結合すると、大量のメモリが消費される可能性があります。最初に小さいデータセットでテストしてください。
-
PDF の互換性:
- すべての入力 PDF が有効であり、破損していないことを確認してください。
-
カスタム除外:
- 必要に応じて、EXCLUDED_DIRS セットを変更して追加のディレクトリを除外します。
結論
このチュートリアルでは、Python を使用してディレクトリ構造からの PDF の結合を自動化する方法を説明します。提供されている CLI ツールは柔軟性があり、より複雑なワークフローに適応できます。試してみて、どのように機能するかお知らせください!
コーディングを楽しんでください! ?
以上がPython を使用して PDF を再帰的に結合するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

Pythonは解釈された言語ですが、コンパイルプロセスも含まれています。 1)Pythonコードは最初にBytecodeにコンパイルされます。 2)ByteCodeは、Python Virtual Machineによって解釈および実行されます。 3)このハイブリッドメカニズムにより、Pythonは柔軟で効率的になりますが、完全にコンパイルされた言語ほど高速ではありません。

useaforloopwhenteratingoverasequenceor foraspificnumberoftimes; useawhileloopwhentinuninguntinuntilaConditionismet.forloopsareidealforknownownownownownownoptinuptinuptinuptinuptinutionsituations whileoopsuitsituations withinterminedationations。

pythonloopscanleadtoErrorslikeinfiniteloops、ModifiningListsDuringiteration、Off-Oneerrors、Zero-dexingissues、およびNestededLoopinefficiencies.toavoidhese:1)use'i

forloopsareadvastountousforknowterations and sequences、offeringsimplicityandeadability;

pythonusesahybridmodelofcompilation andtertation:1)thepythoninterpretercompilessourcodeodeplatform-indopent bytecode.2)thepythonvirtualmachine(pvm)thenexecuteTesthisbytecode、balancingeaseoputhswithporformance。

pythonisbothintersedand compiled.1)it'scompiledtobytecode forportabalityacrossplatforms.2)bytecodeisthenは解釈され、開発を許可します。

loopsareideal whenyouwhenyouknumberofiterationsinadvance、foreleloopsarebetterforsituationsは、loopsaremoreedilaConditionismetを使用します

henthenumber ofiterationsisknown advanceの場合、dopendonacondition.1)forloopsareideal foriterating over for -for -for -saredaverseversives likelistorarrays.2)whileopsaresupasiable forsaresutable forscenarioswheretheloopcontinupcontinuspificcond


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

VSCode Windows 64 ビットのダウンロード
Microsoft によって発売された無料で強力な IDE エディター

メモ帳++7.3.1
使いやすく無料のコードエディター

WebStorm Mac版
便利なJavaScript開発ツール

SublimeText3 中国語版
中国語版、とても使いやすい

SAP NetWeaver Server Adapter for Eclipse
Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。
