0

Why does it add 2 '\' instead of 1 '/'? I am trying to create a cats folder(using Jupyter Notebook) inside the train directory for my model where I will place the cat's images. As it os.path.join returns 2 '\' that is why I am unable to copy/place images there through code. Can anybody help me better understand os.path.join as I have gone through several articles but those were of no help

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

This is what it returns

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

instead of one '/' it returns 2 '\'?

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
Zaid Aly
  • 163
  • 1
  • 17
  • 3
    Backslashes need to be escaped in Python. – Barmar Aug 22 '21 at 19:08
  • 1
    On Windows, the standard directory separator is backslash. – Barmar Aug 22 '21 at 19:08
  • Thank you for your comment @Barmar but why does it add extra backslash? – Zaid Aly Aug 22 '21 at 19:10
  • Python presents the string in the same form as would be needed in Python source code. Your path contains `\train`. In a Python string `"\t"` means a tab character. So if you mean backslash followed by `t` you have to type it as `"\\t"`. This is called "escaping" because you want to escape from the convention that the backslash indicates something special. – BoarGules Aug 22 '21 at 20:35

2 Answers2

1

Looks like you're working on a Windows system.

Running your code on MacOS I get:

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

When you're running on Windows, the directory seprator is \, not /. But, because of Python's escaping, when you print it, you see \\, because Python escapes the slash.

Daniel Trugman
  • 8,186
  • 20
  • 41
0

Probably you're using Windows and while using Python on It you commonly use double backslashes '\'. On unix systems you'll got the '/'.

codan
  • 36
  • 1