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

依旧不行,谢谢。

黄舟
黄舟

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

reply all(2)
伊谢尔伦

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.

阿神

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template