1

I have two functions in my program one will take the path from user and another will open the file in that path, this function will open the file

def pdfparser(filename):
    fp = file(filename, 'rb')

when I pass the path from another function it returns:

IOError: [Errno 22] invalid mode ('rb') or filename:'C:\\Users\\user\\PycharmProjects\\advisor\\website\\a.PDF

I know I have to add double splash to the path or (r'path) but my question how can I add r' or double slash into variable since the path will be stored in variable and pass into another function. I need something like s=r'path

any help please

16
  • 3
    The r prefix is only for constants. Once the string has the correct value, no need to specify r prefix again. Are you sure the file exists on your system? Try to print filename just before opening it, and copy/paste it in a windows explorer to see it windows finds it. Commented Jul 4, 2016 at 20:37
  • 1
    I am not sure I understand the question (is the IOError really complete? What about the stacktrace), but what does not work with filename = r'C:\Users\user\PycharmProjects\advisor\website\a.PDF besides os.path.join() being far cooler ...? Commented Jul 4, 2016 at 20:38
  • Your error indicates the filename was correctly specified; all the backslashes are correct. The problem you have is not one that can be solved with prefixing r somewhere. Note that r'...' is just a syntax to specify a string value, it is not a separate object type. It just tells the parser not to interpret \.. escape sequences. Because this is a syntax concept there is no dynamic counterpart. Commented Jul 4, 2016 at 20:44
  • @Jean-François Fabre it exists I have tried that but when I pass 'C:\Users\user\PycharmProjects\advisor\website\a.PDF it does not work but when I add double slash or r' works but the idea my path is sorted within a variable so how can I add r' or double space Commented Jul 4, 2016 at 20:48
  • @Dilettant I can't add r' into path because my path within variable in another function Commented Jul 4, 2016 at 20:53

1 Answer 1

1

Do this:

Before calling this function, store the path value in any variable say, 'directory', here u add the prefix r' in filepath. When calling this pdfparser(filename) function, just pass 'directory' as argument. It works!

>directory= r"C:\Users\SomeUser\Pictures\Disk"  
>pdfparser(directory)
Sign up to request clarification or add additional context in comments.

1 Comment

At first sight, I was afraid this could not work. But after tested it, it just worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.