2016-12-02 25 views
0

我試圖編寫一個簡單的腳本來合併兩個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行, ,而不是字節

我哪裏出錯了?

+0

您可以發佈全堆棧跟蹤,而不僅僅是信息? –

+0

請不要在評論中發佈堆棧痕跡。您的問題有一個「編輯」鏈接,可讓您編輯問題。 –

回答

1

嘗試使用tk.filedialog.asksaveasfilename而不是tk.filedialog.asksaveasfile。你只需要文件名,而不是文件處理程序本身。

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

有了,我得到了錯誤「AttributeError的:‘海峽’對象有沒有屬性‘寫’」於是我加 '開放的(「output_name中」,「世行」)爲節省: \t output.write(保存)' 它不會給出任何錯誤,但不會寫PDF。 – pgcudahy

1

我通過向tk.filedialog.asksaveasfile添加mode ='wb'來得到它。現在是

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