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

前端 未结 1 411
青春惊慌失措
青春惊慌失措 2021-01-23 01:10

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 i

1条回答
  •  -上瘾入骨i
    2021-01-23 01:38

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

    0 讨论(0)
提交回复
热议问题