Jupyter 上没有这样的文件或目录:'Tensorflow/workspace/annotations\\label_map.pbtxt 为什么我的代码不起作用?

No such file or directory: 'Tensorflow/workspace/annotations\\label_map.pbtxt on Jupyter why is my code not working?

我正在关注此视频 Real Time Face Mask Detection with Tensorflow and Python

但是,在视频 21:06 中,当开发人员创建“标签映射文件”时,我的文件并未在我的本地计算机上创建,我在 Jupyter 上收到一条错误消息 **FileNotFoundError: [Errno 2] No such file or directory: 'Tensorflow/workspace/annotations\label_map.pbtxt'**.

正如您从下面的屏幕截图中看到的,我已经复制了视频中的代码我认为我没有在 Jupyter 上错误地复制它。

我的代码

labels = [{'name':'Mask', 'id':1}, {'name':'NoMask', 'id':2}]
     
with open(ANNOTATION_PATH + '/label_map.pbtxt', 'w') as f:
    for label in labels:
        f.write('item { \n')
        f.write('\tname:\'{}\'\n'.format(label['name']))
        f.write('\tid:{}\n'.format(label['id']))
        f.write('}\n')

教程代码 - 21:06 - 创建地图文件

tutorial code on jupyter.

正如您从下面的下一个屏幕截图中看到的那样,我的路径应该都是正确的我不明白为什么没有创建“标签地图”文件?

No label map file was created

我也尝试过以不同的方式为文件路径放置斜杠,例如 /\.

看起来你有多余的斜线 \。只需删除一个斜杠。

使用带盘符的绝对路径,例如r'C:\Users\NaziModerator\Tensorflow\workspace\annotations\label_map.pbtxt'.

不要混用 \/

不要忘记字符串前的 r''

print(path) 确定。

TL;DR 使用 os.path.join 连接路径元素,或 pathlib.PurePath 清除混合路径变量

方案一:使用os.path.join

当您在 Python 中构造文件路径名时,最安全的做法是在每一步都使用 os.path.join()。这将始终为您提供可移植代码。

例如:

import os

ANNOTATION_PATH = os.path.join("Tensorflow", "workspace", "annotations")
with open(os.path.join(ANNOTATION_PATH, "label_map.pbtxt", "w") as f:
    ...

如果你在 Windows-native Python 解释器中 运行 这段代码,你会看到路径组件被系统地按 \ 分割,因为它们应该是这样,如果您 运行 在 Linux 或 Cygwin Python 解释器中使用相同的代码,您将在路径组件之间看到 /

参考:os.path.join in the Python manual

方案二:使用pathlib.PurePath

Python 中的 pathlib 库可用于为您清理混合的 slash/backslash 路径。

测试于 Windows:

>>> import pathlib
>>> print(pathlib.PurePath('Tensorflow/workspace/annotations\label_map.pbtxt'))
Tensorflow\workspace\annotations\label_map.pbtxt

参考:pathlib in the Python manual