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

Issue

I’m following this video Real Time Face Mask Detection with Tensorflow and Python.

However, at the point in the video 21:06 when the developer creates the "Label map file" my file doesn’t create on my local machine and I get an error on Jupyter which says **FileNotFoundError: [Errno 2] No such file or directory: 'Tensorflow/workspace/annotations\\label_map.pbtxt'**.

As you can see from the screenshot below, I have copied the code in the video I don’t think I copied it over incorrectly on Jupyter.

MY CODE

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')

TUTORIAL CODE – 21:06 – CREATE MAP FILE

tutorial code on jupyter.

As you can see from the next screenshot below, my path should be all correct I don’t understand why the "label map" file is not creating?

No label map file was created

I have also tried putting the slash in different ways for the file path like this / and this \.

Solution

TL;DR Use os.path.join to join path elements, or pathlib.PurePath to clean a mixed path variables

Solution 1: use os.path.join

When you are constructing file path names in Python, the safest thing to do is to use os.path.join() at every step. This will always give you portable code.

For example:

import os

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

If you run this code in a Windows-native Python interpreter, you will see that path components are systematically divided by \ as they should be, and if you run the same code on Linux or in a Cygwin Python interpreter, you will see / between path components.

Ref: os.path.join in the Python manual

Solution 2: use pathlib.PurePath

The pathlib library in Python can be used to clean up mixed slash/backslash paths for you.

Tested on Windows:

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

Ref: pathlib in the Python manual

Answered By – joanis

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published