【发布时间】:2017-04-17 03:36:31
【问题描述】:
我正在尝试编写一个简单的脚本来合并两个 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
问题是我得到一个错误
用户警告:要写入的文件不是二进制模式。它可能没有正确写入。 [pdf.py:453] Traceback(最近一次调用最后一次):文件“Combine2Pdfs.py”,第 44 行,在 output.write(output_name) 文件“/Library/Frameworks/Python.framework/Versions/3.5/lib/pytho”中n3.5/site-packages/PyPDF2/pdf.py",第 487 行,写入 stream.write(self.header + b("\n")) TypeError: write( ) 参数必须是 str,而不是字节
我哪里出错了?
【问题讨论】:
-
你能发布完整的堆栈跟踪,而不仅仅是消息吗?
-
请不要在评论中发布堆栈跟踪。您的问题有一个“编辑”链接,可让您编辑问题。
标签: python-3.x pdf pypdf2