我試圖編寫一個簡單的腳本來合併兩個PDF,但在嘗試將輸出保存到磁盤時遇到問題。我的代碼是使用pypdf2編寫PDF給出了錯誤
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
的問題是,我得到的
UserWarning錯誤:文件寫的不是二進制模式。它可能無法正確寫入。 [pdf.py:453]追溯(最近調用最後一個):在output.write(output_name)文件中的文件「Combine2Pdfs.py」,第44行,文件「/Library/Frameworks/Python.framework/Versions/3.5/lib/pytho寫入stream.write(self. header + b(「\ n」))TypeError:write()參數必須是str(n3.5/site-packages/P yPDF2/pdf.py),第487行, ,而不是字節
我哪裏出錯了?
您可以發佈全堆棧跟蹤,而不僅僅是信息? –
請不要在評論中發佈堆棧痕跡。您的問題有一個「編輯」鏈接,可讓您編輯問題。 –