2015-11-21 52 views
0

目標=打開文件,加密文件,寫入加密文件。
嘗試使用PyPDF2模塊來完成此操作。我已經驗證過「輸入」是一個文件類型的對象。我研究了這個錯誤,它轉化爲「找不到文件」。我相信它以某種方式與文件/文件路徑鏈接,但我不確定如何調試或排除故障。並得到以下錯誤:PyPDF2 IOError:[Errno 22] PyPdfFileReader上的無效參數Python 2.7

Traceback (most recent call last): 
    File "CommissionSecurity.py", line 52, in <module> 
    inputStream = PyPDF2.PdfFileReader(input) 
    File "build\bdist.win-amd64\egg\PyPDF2\pdf.py", line 1065, in __init__ 
    File "build\bdist.win-amd64\egg\PyPDF2\pdf.py", line 1660, in read 
IOError: [Errno 22] Invalid argument 

下面是相關的代碼。我不知道如何解決這個問題,因爲我不確定問題是什麼。任何指導表示讚賞。

for ID in FileDict: 
     if ID in EmailDict : 
      path = "C:\\Apps\\CorVu\\DATA\\Reports\\AlliD\\Monthly Commission Reports\\Output\\pdcom1\\" 
      #print os.listdir(path) 
      file = os.path.join(path + FileDict[ID]) 

      with open(file, 'rb') as input: 
       print type(input) 
       inputStream = PyPDF2.PdfFileReader(input) 
       output = PyPDF2.PdfFileWriter() 
       output = inputStream.encrypt(EmailDict[ID][1]) 
      with open(file, 'wb') as outputStream: 
       output.write(outputStream) 
     else : continue 
+0

@Evert我根據您的建議重構,證實PdfFileWriter正確使用,並糾正了inputStream問題。我還驗證了「文件」是一個文件類型對象。我繼續得到相同的錯誤。 – AlliDeacon

回答

0

使用open(文件, 'RB')是導致監守PdfFileReader問題()這是否自動的。我剛剛刪除了與聲明,並糾正了這個問題。

with open(file, 'rb') as input: 
    inputStream = PyPDF2.PdfFileReader(input) 
1

我覺得你的問題可能是你使用相同的文件名來打開和寫入文件的事實造成的,打開它兩次:

with open(file, 'rb') as input : 
    with open(file, 'wb') as outputStream : 

w模式將截斷文件,因此第二行會截斷輸入。
我不確定你的意圖是什麼,因爲你不能真正嘗試從文件的(開始)讀取,並且同時覆蓋它。即使您嘗試寫入文件末尾,也必須將文件指針放在某處。 因此,創建一個具有不同名稱的額外輸出文件;在兩個文件關閉後,您總是可以將輸出文件重命名爲輸入文件,從而覆蓋輸入文件。

或者你可以先閱讀完整的文件到內存,然後寫它:

with open(file, 'rb') as input: 
    inputStream = PyPDF2.PdfFileReader(input) 
    output = PyPDF2.PdfFileWriter() 
    output = input.encrypt(EmailDict[ID][1]) 
with open(file, 'wb') as outputStream: 
    output.write(outputStream) 

注:

  • 分配inputStream,但從來沒有使用它
  • 分配PdfFileWriter()output,然後在下一行分配其他內容到output。因此,您從未使用第一行output =行的結果。

請仔細檢查你在做什麼,因爲它感覺你的代碼有許多其他問題。


另外,這裏有一些小竅門,可以幫助:

documentation建議您也可以使用文件名作爲第一個參數PdfFileReader:

stream – A File object or an object that supports the standard read and seek methods similar to a File object. Could also be a string representing a path to a PDF file.

所以嘗試:

inputStream = PyPDF2.PdfFileReader(file) 

您還可以嘗試設置strict參數False

strict (bool) – Determines whether user should be warned of all problems and also causes some correctable problems to be fatal. Defaults to True.

例如:

inputStream = PyPDF2.PdfFileReader(file, strict=False) 
+0

這很有道理。我將使用你的建議重新配置,如果它解決了我的問題,請標記你的答案。非常感謝! – AlliDeacon

+0

@AlliDeacon但看到我最近的「註釋」點。 – Evert

+0

我的理解是輸出= PyPDF2.PdfFileWriter()初始化輸出能夠被寫入。我肯定會澄清這一點。我嘗試了很多解決方案,InputStream必須是一個失敗者。我會在早上用新鮮的眼睛重新審視。感謝您的意見和協助。 – AlliDeacon

相關問題