0

I'm trying to write a simple script to merge two PDFs but have run into an issue when trying to save the output to disk. My code is

from PyPDF2 import PdfFileWriter, PdfFileReader
import tkinter as tk
from tkinter import filedialog    

### Prompt the user for the 2 files to use via GUI ###
root = tk.Tk()
root.update()
file_path1 = tk.filedialog.askopenfilename(
            filetypes=[("PDF files", "*.pdf")],
            )

file_path2 = tk.filedialog.askopenfilename(
            filetypes=[("PDF files", "*.pdf")],
            )

###Function to combine PDFs###
output = PdfFileWriter()

def append_pdf_2_output(file_handler):
    for page in range(file_handler.numPages):
        output.addPage(file_handler.getPage(page))

#Actually combine the 2 PDFs###
append_pdf_2_output(PdfFileReader(open(file_path1, "rb")))
append_pdf_2_output(PdfFileReader(open(file_path2, "rb")))

###Prompt the user for the file save###
output_name = tk.filedialog.asksaveasfile(
            defaultextension='pdf')

###Write the output to disk###
output.write(output_name)
output.close

The problem is that I get an error of

UserWarning: File to write to is not in binary mode. It may not be written to correctly. [pdf.py:453] Traceback (most recent call last): File "Combine2Pdfs.py", line 44, in output.write(output_name) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/pytho‌​n3.5/site-packages/P‌​yPDF2/pdf.py", line 487, in write stream.write(self.header + b("\n")) TypeError: write() argument must be str, not bytes

Where have I gone wrong?

2
  • can you post full stacktrace, not just the message? Commented Dec 2, 2016 at 9:21
  • please don't post stack traces in the comment. Your question has an "edit" link that lets you edit the question. Commented Dec 2, 2016 at 12:32

2 Answers 2

2

I got it by adding mode = 'wb' to tk.filedialog.asksaveasfile. Now it's

output_name = tk.filedialog.asksaveasfile(
        mode = 'wb',
        defaultextension='pdf')
output.write(output_name)
1

Try to use tk.filedialog.asksaveasfilename instead of tk.filedialog.asksaveasfile. You just want the filename, not the file handler itself.

###Prompt the user for the file save###
output_name = tk.filedialog.asksaveasfilename(defaultextension='pdf')
1
  • With that I got the error "AttributeError: 'str' object has no attribute 'write'" So then I added with open("output_name", 'wb') as save: output.write(save) which doesn't give any errors but doesn't write the pdf either.
    – pgcudahy
    Commented Dec 5, 2016 at 6:44

Not the answer you're looking for? Browse other questions tagged or ask your own question.