2013-06-29 56 views
0

我需要刪除目錄中多個pdf文件的第一頁。我是一個初級的python用戶,我已經拼湊了下面的代碼,它們來自我擁有的其他代碼的&部分。但是,我無法讓它工作。任何人都會跳出來嗎?如何刪除目錄中多個pdf文件的第一頁? PYTHON

from PyPDF2 import PdfFileWriter, PdfFileReader 

import os, sys 

directory_name = 'emma' 


for filename in directory_name: 
    print 'name: %s' % filename 

    output_file = PdfFileWriter() 
    input_handle = open(filename+'.pdf', 'rb') 
    input_file = PdfFileReader(input_handle) 

    num_pages = input_file.getNumPages() 

    print "document has %s pages \n" % num_pages 

    for i in xrange(1, num_pages): 
     output_file.addPage(input_file.getPage(i)) 
     print 'added page %s \n' % i 

    output_stream = file(filename+'-stripped.pdf','wb') 
    output_file.write(output_stream) 

    output_stream.close() 
    input_handle.close() 

錯誤消息:在 「愛瑪」

input_handle = open(filename+'.pdf', 'rb') 
     IOError: [Errno 2] No such file or directory: 'a.pdf' 
+0

首先,請說明「無法正常工作」的含義。其次,假設第一個問題的答案是「產生的文檔被創建但是不完整」,檢查讀者和寫者對象的內部(也許,有一個潛在的「文檔」對象),以查看第二個中缺少的內容。我想這是除了頁面之外的其他實體。 –

+0

嗯,我得到一個錯誤是:input_handle = open(filename +'.pdf','rb'> IOError:[Errno 2]沒有這樣的文件或目錄:'a.pdf' –

+0

然後它正是它的內容:操作系統無法找到您傳遞給open()調用的文件路徑,甚至沒有連接到「PyPDF2」。請在網上提問並讓其他人浪費之前做一些合理的初步診斷和/或自行搜索他們在他們身上的時間 –

回答

0

你的代碼循環並嘗試打開e.pdfm.pdf(兩次),a.pdf。您在a.pdf上的錯誤意味着前兩個確實存在,這對自己來說足夠有趣。

但是對於您的問題,您需要使用os.listdirglob來實際獲取目錄中的文件名。

+0

非常感謝您的幫助,請嘗試一下。 –

相關問題