Cannot merge pdf in python v3.6

Question:

I have the following code segment which has been tested to work in python ver2.7
The code merges multiple pdfs into a single pdf.

from PyPDF2 import PdfFileMerger, PdfFileReader

#merge individual pdfs of each page into a single pdf
merger = PdfFileMerger()
for filename in pdf_list:
    merger.append(PdfFileReader(file("./" + pdf_location + "/" + filename, 'rb')))

When I run the same code in python v3.6, it fails and the following error is printed.

NameError: name 'file' is not defined

How should the code be modified to get it working in python v3.6?

Asked By: user3848207

||

Answers:

I haven’t used PdfFileReader before, but from the documentation, it requires a filestream as an argument. So try changing “file” to “open” which should pass on a filestream pointed to the location in the read binary mode to the PdfFileReader constructor. So your append line should read as follows:

merger.append(PdfFileReader(open("./" + pdf_location + "/" + filename, 'rb')))
Answered By: Partha Das
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.