Jona
Jona

Reputation: 21

The open() functions doesn't behave correctly with filepath containing special characters

I'm writing this simple code:

file = input('File to read: ')
fhand = open(file, 'r')

The file I want to open is called 'test.txt', and it is located in a subfolder; what I put into the requested input therefore is: 'DB\test.txt'.

Well: it doesn't work, returning this error message:

OSError: [Errno 22]Invalid argument: 'DB\test.txt'.

I have another file in the same directory, called 'my_file.txt', and I don't get errors attempting to open it. Lastly I have another file, called 'new_file.txt', and this one also gets me the same error.

What seems obvious to me is that the open() function reads the "\t" and the "\n" as if they were special characters; searching on the web I found nothing that really could help me avoiding special characters within user input strings... Could anybody help?

Thanks!

Upvotes: 2

Views: 70

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140188

you'll have no problems with Python 3 with your exact code (this issue is often encountered when passing windows literal strings where the r prefix is required).

With python 2, first you'll have to wrap your filename with quotes, then all special chars will be interpreted (\t, \n ...). Unless you input r"DB\test.txt" using this raw prefix I was mentionning earlier but it's beginning to become cumbersome :)

So I'd suggest to use raw_input (and don't input text with quotes). Or python version agnostic version to override the unsafe input for python 2 only:

try:
    input = raw_input
except NameError:
    pass

then your code will work OK and you got rid of possible code injection in your code as a bonus (See python 2 specific topic: Is it ever useful to use Python's input over raw_input?).

Upvotes: 2

Related Questions