Use Python Traverse Directories and Merge PDFs

html

Background Info

Iterating through directories is a key part in file manipulation and automating certain actions, or finding a file type. Python provides several methods to traverse a directory, and includes:

  1. os.listdir()
  2. os.scandir()
  3. os.walk()
  4. glob

Why is this important?
Traversing directories is a useful technique when you need to automate a process.

Goal
The goal of this post is to demonstrate how to traverse a directory and merge PDF files in each directory. This is an example of how tedious work can be automated. One of the tasks I've had at work is to prepare multiple documents for payment processing, but they needed to be saved in unique folders, and the files used to prepare the final payment documents need to be merged. Having to manually do this is labor intensive, and a big waste of time. This simple code works for cases where you just need to merge several pdf files, and you are traversing folders in the same directory. If you have hundreds of folders,this code will need to be optimized (perhaps running by blobs).


Create a function that will traverse folders and merge PDF files.


Import Dependencies Explained.


Code to merge PDFs explained.


Folder selection code explained.


Function to traverse folders, and Merge PDFs.


Run code explained.