【问题标题】:Python Path Double Backslash when opening file causing error打开文件时Python路径双反斜杠导致错误
【发布时间】: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


【解决方案1】:

不太清楚为什么要添加两个反斜杠。您可以使用单个正斜杠(基于 Linux)或反斜杠(win)简单地创建路径。像这样的:

script_path = os.path.dirname(os.path.realpath(__file__)) + '/tmp/description.xml'

但是,实现此目的的更好方法是按照 nomansland008 的建议使用 os.path.join

>>> import os

>>> parent_dir = "xyz"
>>> dir = "foo"
>>> file_name = "bar.txt"
>>> os.path.join(parent_dir, dir, file_name)
'xyz/foo/bar.txt'

您不必担心字符串是否有斜线(或没有)。它将由加入来处理。 在您的情况下,它可以简单地是:

os.path.join(os.path.dirname(os.path.realpath(__file__)), 'tmp', 'description.xml')

如果文件和目录存在,应该可以工作。

【讨论】:

    猜你喜欢
    • 2014-04-29
    • 2013-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-25
    • 1970-01-01
    • 2014-02-04
    • 2017-03-16
    相关资源
    最近更新 更多