Search code examples
pythonpython-2.7pypdf

PyPDF2 IOError: [Errno 22] Invalid argument on PyPdfFileReader Python 2.7


Goal = Open file, encrypt file, write encrypted file.
Trying to use the PyPDF2 module to accomplish this. I have verified theat "input" is a file type object. I have researched this error and it translates to "file not found". I believe that it is linked somehow to the file/file path but am unsure how to debug or troubleshoot. and getting the following error:

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

Below is the relevant code. I'm not sure how to correct this issue because I'm not really sure what the issue is. Any guidance is appreciated.

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

Solution

  • Using open(file, 'rb') was causing the issue becuase PdfFileReader() does that automagically. I just removed the with statement and that corrected the problem.

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