Maison  >  Questions et réponses  >  le corps du texte

请教: 关于 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 Il y a quelques jours540

répondre à tous(2)je répondrai

  • 伊谢尔伦

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

    Le nom du fichier est OK : le premier dans '\' est le caractère d'échappement. Vous pouvez l'essayer avec print(a).

    Si vous souhaitez utiliser f.write, vous devez ouvrir le fichier via open(a, 'w'):

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

    De plus, f.close() est redondant si vous l'utilisez avec.

    répondre
    0
  • 阿神

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

    a = r'D:githubdjangosamplefoo.txt'

    répondre
    0
  • Annulerrépondre