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('\\\\','\\')
依旧不行,谢谢。
伊谢尔伦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.