【发布时间】:2020-07-03 10:00:49
【问题描述】:
我正在尝试打开这样的文件:
with open(str(script_path) + '\\description.xml', 'w+') as file:
其中script_path 等于:
script_path = os.path.dirname(os.path.realpath(__file__)) + '\\.tmp')
当我运行它时,我收到一个错误,即没有这样的文件或目录,因为当它尝试打开文件时,它会将整个路径视为一个字符串,包括转义字符串。有没有办法解决?
显然.replace() 在这里不起作用,因为它不会替换转义字符串。希望在 os 模块中有一个聪明的方法来做到这一点?
【问题讨论】:
-
为什么有两个反斜杠?如果
description.xml与脚本在同一目录下,则相对路径就是description.xml -
我想我这样做是为了让它在 tmp 文件夹中,虽然我想我可以使用
'.tmp/description.xml' -
我建议使用 os.path.join 创建路径而不是字符串连接。这可能有助于避免这个问题。
标签: python path operating-system