Python script to merge PDF Files | Daily Python #28

Ajinkya Sonawane
Daily Python
Published in
3 min readFeb 13, 2020

--

This article is a tutorial on how to merge PDF files using Python.

This article is a part of Daily Python challenge that I have taken up for myself. I will be writing short python articles daily.

Requirements:

  1. Python 3.0
  2. Pip

Install the following packages:

  1. PyPDF2 — PDF toolkit based on Python
pip install PyPDF2

Let’s import the required modules

from os import listdir,mkdir,startfile
from os.path import isfile, join,exists
from PyPDF2 import PdfFileMerger
  1. listdir — used to list the files in the given directory
  2. mkdir — used to create a new directory
  3. startfile — used to launch a file
  4. isfile — used to check if an input is a file
  5. join — used to join one or more path components intelligently
  6. exists — used to check if a folder or file exists
  7. PDFFileMerger — used to merge the pdf files

Let’s take the path from where the PDF files are to be fetched and print the file names

#Input file path and print the pdf files in that path
path = input("Enter the folder location: ")
pdffiles = [f for f in listdir(path) if isfile(join(path, f)) and '.pdf' in f]
print('\nList of PDF Files:\n')
for file in pdffiles:
print(file)

Accept the name of the result file

#Input the name of the result file
resultFile = input("\nEnter the name of the result file : ")
if '.pdf' not in resultFile:
resultFile += '.pdf'

Traverse through the pdf files and append them

#Append the pdf files
merger = PdfFileMerger()
for pdf in pdffiles:
merger.append(path+'\\'+pdf)

Create an Output directory if none exists

#If the Output directory does not exist then create one
if not exists(path+'\\Output'):
mkdir(path+'\\Output')

Now, merge the files and write it to the output directory

#Write the merged result file to the Output directory
merger.write(path+'\\Output\\'+resultFile)
merger.close()

Finally, we launch the result file, a merged pdf of the given pdf files

#Launch the result file
print('\n'+resultFile,'Successfully created!!! at ',path+'\\Output\\')
startfile(path+'\\Output\\'+resultFile)
The above code snippet in action

I hope this article was helpful, do leave some claps if you liked it.

Follow the Daily Python Challenge here:

--

--