I’m trying to open a PDF file with spaces in its filename and, possibly, in its path. I’m working on Windows.

from PyPDF2 import PdfReader

def main():
    
    path = input( 'Whatever: ' )
    reader = PdfReader( path )

‘Whatever’ is actually a string asking the user to drag-and-drop a file on the terminal window, so that its full path is given as input to the script. On input C:\Users\example input.pdf I get the following error:

Traceback (most recent call last):
  File "C:\Users\[REDACTED]\test.py", line 119, in <module>
    main()
  File "C:\Users\[REDACTED]\test.py", line 20, in main
    reader = PdfReader( path )
             ^^^^^^^^^^^^^^^^^
  File "C:\Users\[REDACTED]\anaconda3\envs\delete_later\Lib\site-packages\PyPDF2\_reader.py", line 317, in __init__
    with open(stream, "rb") as fh:
         ^^^^^^^^^^^^^^^^^^
OSError: [Errno 22] Invalid argument: '"C:\\Users\\example input.pdf"'

I tried lots of stuff, but the only two things that worked are:

  • remove whitespace from filename – acceptable when whitespace only occurs in its filename, unacceptable if it also occurs in its path
  • don’t ask the user for a path – completely unacceptable

is there any other workaround? Or even a solution?