SyntaxError when trying to use backslash for Windows file path

前端 未结 3 1808
灰色年华
灰色年华 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:52

    You get the problem with the 2 character sequences \x and \U -- which are python escape codes. They tell python to interpret the data that comes after them in a special way (The former inserts bytes and the latter unicode). You can get around it by using a "raw" string:

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

    or by using forward slashes (as, IIRC, windows will accept either one).

提交回复
热议问题