请教: 关于 python 反斜杠转义的疑问
黄舟
黄舟 2017-04-18 10:28:34
0
2
533
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('\\\\','\\')

依旧不行,谢谢。

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

répondre à tous(2)
伊谢尔伦

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.

阿神

a = r'D:githubdjangosamplefoo.txt'

Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!