Daily Python
Published in

Daily Python

Python script to merge PDF Files | Daily Python #28

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


  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:

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:

Create an Output directory if none exists

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

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

#Write the merged result file to the Output directory

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\\')
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:



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store