2016-12-02 1 views
0

두 개의 PDF를 병합하는 간단한 스크립트를 작성하려고하지만 출력을 디스크에 저장하려고 할 때 문제가 발생했습니다. 바이너리 모드가 아닌 쓸 파일 : 내 코드는 문제는 내가pypdf2로 pdf를 작성하면 오류가 발생합니다.

UserWarning의 오류가 있다는 것입니다

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 (최근 호출 마지막) : 44 행의 output.write (output_name) 파일에서 "Combine2Pdfs.py"파일 "/Library/Frameworks/Python.framework/Versions/3.5/lib/pytho ("\ n")) TypeError : write() 인수는 str이어야합니다. (예 : \ n3.5/site-packages/P yPDF2/pdf.py ", 487 줄, write stream.write (self. header + b , 바이트가 아님

어디서 잘못 되었나요?

+0

메시지뿐 아니라 전체 스택 트레이스를 게시 할 수 있습니까? –

+0

주석에 스택 추적을 게시하지 마십시오. 질문에 "편집"링크가있어 질문을 수정할 수 있습니다. –

답변

1

tk.filedialog.asksaveasfile 대신 tk.filedialog.asksaveasfilename을 사용해보십시오. 파일 핸들러 자체가 아니라 파일 이름 만 원한다.

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

"AttributeError : 'str'개체에 '쓰기'속성이 없습니다. 그러면 열기 ("output_name ", 'wb')를 사용하여 을 저장합니다. \t output.write (save) 어떤 오류도주지 않지만 pdf도 쓰지 않습니다. – pgcudahy

1

tk.filedialog.asksaveasfile에 mode = 'wb'를 추가하여 얻은 것입니다. 지금은

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