【问题标题】:Why os.path.join returns result with 2 slashes? [duplicate]为什么 os.path.join 返回带有 2 个斜杠的结果? [复制]
【发布时间】:2023-04-10 20:35:01
【问题描述】:

为什么要加 2 个 '\' 而不是 1 个 '/'? 我正在尝试在我的模型的火车目录中创建一个猫文件夹(使用 Jupyter Notebook),我将在其中放置猫的图像。因为它 os.path.join 返回 2 '\' 这就是为什么我无法通过代码复制/放置图像。任何人都可以帮助我更好地理解 os.path.join,因为我已经阅读了几篇文章,但这些都没有帮助

base_dir = "CNN_Working/cats_and_dogs_small"
train_dir = os.path.join(base_dir, 'train')
os.mkdir(train_dir)

train_cats_dir = os.path.join(train_dir, 'cats')
os.mkdir(train_cats_dir)

train_cats_dir

这是它返回的内容

'CNN_Working\\cats_and_dogs_small\\train\\cats'

返回 2 '\' 而不是一个 '/'?

【问题讨论】:

  • Python 中需要对反斜杠进行转义。
  • 在 Windows 上,标准的目录分隔符是反斜杠。
  • 感谢您的评论@Barmar,但为什么要添加额外的反斜杠?
  • Python 以与 Python 源代码中所需的相同形式呈现字符串。您的路径包含\train。在 Python 字符串中,"\t" 表示制表符。因此,如果您的意思是反斜杠后跟t,则必须将其键入为"\\t"。这称为“转义”,因为您想摆脱反斜杠表示特殊内容的约定。

标签: python os.path path-separator


【解决方案1】:

看起来您正在使用 Windows 系统。

在 MacOS 上运行你的代码我得到:

(base) X 68884371 % python3 script.py
CNN_Working/cats_and_dogs_small/train
CNN_Working/cats_and_dogs_small/train/cats

在 Windows 上运行时,目录分隔符是 \,而不是 /。 但是,由于 Python 的转义,当您打印它时,您会看到 \\,因为 Python 转义了斜杠。

【讨论】:

    【解决方案2】:

    可能您使用的是 Windows,而在其上使用 Python 时,您通常使用双反斜杠“\”。在 unix 系统上,您将获得 '/'。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-16
      • 1970-01-01
      • 1970-01-01
      • 2020-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-17
      相关资源
      最近更新 更多