Home  >  Q&A  >  body text

请教: 关于 python 反斜杠转义的疑问

a = 'D:\\github\\django\\sample\\foo.txt'
# a为foo.txt的路径,通过os.path生成
with open(a) as f:
    f.write("Hello")
    f.close()

当我执行上面这个片段的时候,提示找不到文件:'D:\\github\\django\\sample\\foo.txt',我觉得应该是这种路径分隔符在windows下没有被正确解析,于是:

a.replace('\\','\')
#我期待的结果是把路径转化为  D:\github\django\sample\foo.txt.

结果提示:

SyntaxError: EOL while scanning string literal

于是想请教一下我该怎样正确转义或者通过其他方法达到预期的效果呢?
我试过:

a.replace('\\',r'\')
a.replace('\\\\','\\')

依旧不行,谢谢。

黄舟黄舟2741 days ago535

reply all(2)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-18 10:30:34

    The file name is OK: the first one in '\' is the escape character. You can try it with print(a).

    If you want to use f.write, you should open the file through open(a, 'w'):

    with open(a, 'w') as f:
        f.write("Hello")

    In addition, f.close() is redundant if you use with.

    reply
    0
  • 阿神

    阿神2017-04-18 10:30:34

    a = r'D:\github\django\sample\foo.txt'

    reply
    0
  • Cancelreply