SyntaxError when trying to use backslash for Windows file path

前端 未结 3 1932
灰色年华
灰色年华 2021-01-18 22:22

I tried to confirm if a file exists using the following line of code:

os.path.isfile()

But I noticed if back slash is used by copy&past

3条回答
  •  误落风尘
    2021-01-18 22:54

    Backslash is the escape symbol. This should work:

    os.path.isfile("C:\\Users\\xxx\\Desktop\\xxx")
    

    This works because you escape the escape symbol, and Python passes it as this literal:

    "C:\Users\xxx\Desktop\xxx"
    

    But it's better practice and ensures cross-platform compatibility to collect your path segments (perhaps conditionally, based on the platform) like this and use os.path.join

    path_segments = ['/', 'Users', 'xxx', 'Desktop', 'xxx']
    os.path.isfile(os.path.join(*path_segments))
    

    Should return True for your case.

提交回复
热议问题