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

有些话、适合烂在心里 提交于 2019-12-02 02:15:43

问题


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!


回答1:


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?).



来源:https://stackoverflow.com/questions/52722004/the-open-functions-doesnt-behave-correctly-with-filepath-containing-special-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!