Strange path separators on Windows

前端 未结 6 827
臣服心动
臣服心动 2020-12-18 07:44

I an running this code:

#!/usr/bin/python      coding=utf8
#  test.py = to demo fault
def loadFile(path):
    f = open(path,\'r\')
    text = f.read()
    re         


        
相关标签:
6条回答
  • 2020-12-18 08:14

    The backslash \ is an escape character in Python. So your actual filepath is going to be D:\work\Kindle\srcs<tab>est1.html. Use os.sep, escape the backslashes with \\ or use a raw string by having r'some text'.

    0 讨论(0)
  • 2020-12-18 08:14

    Gotcha — backslashes in Windows filenames provides an interesting overview.

    0 讨论(0)
  • 2020-12-18 08:21

    You need to escape backslashes in paths with an extra backslash... like you've done for '\\test1.html'.

    '\t' is the escape sequence for a tab character.

    'D:\work\Kindle\srcs\test1.html is essentially 'D:\work\Kindle\srcs est1.html'.

    You could also use raw literals, r'\test1.html' expands to:

    '\\test1.html'
    
    0 讨论(0)
  • 2020-12-18 08:22

    The backslash is an escape character when the next character combination would result in a special meaning. Take the following examples:

    >>> '\r'
    '\r'
    >>> '\n'
    '\n'
    >>> '\b'
    '\x08'
    >>> '\c'
    '\\c'
    >>>
    

    r, n, and b all have special meanings when preceded by a backslash. The same is true for t, which would produce a tab. You either need to A. Double all your backslashes, for consistency, because '\\' will produce a backslash, or, B, use raw strings: r'c:\path\to\my\file.txt'. The preceding r will prompt the interpreter not to evaluate back slashes as escape sequences, preventing the \t from appearing as a tab.

    0 讨论(0)
  • 2020-12-18 08:22

    Use raw strings for Windows paths:

    path = r'D:\work\Kindle\srcs\test1.html'
    

    Otherwise the \t piece of your string will be interpreted as a Tab character.

    0 讨论(0)
  • 2020-12-18 08:27

    In addition to using a raw string (prefix string with the r character), the os.path module may be helpful to automatically provide OS-correct slashes when building a pathname.

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