1

I'm having troubles creating directories when concatenating one or more strings as part of the filename. As an example:

DIR = r"D:/My/Directory"
classes = ['itemA', 'itemB']


for item in classes:
    for scope in ["training/", "testing/"]:
        os.mkdir(os.path.join(DIR, scope + item))

Creates the error:

FileNotFoundError: [WinError 3] The system cannot find the path specified: 'D:/My/Directory\\training/itemA'

The os.mkdir works when I'm not using scope + item, but when I do it throws this error. I'm not sure how the function handles training/itemA differently than trainingitemA when they are both interpreted as a string literal.

Jamie Dimon
  • 467
  • 4
  • 16
  • Are you on windows and using forward slashes (`/`)? Shouldn't they be backwards? I'm not using windows but this seems wrong to me. – Asocia May 14 '20 at 22:57

1 Answers1

1

The path separator on Windows is \ and not /, also you can use os.path.join again to join the scope to the item:

DIR = r"D:\My\Directory"
classes = ['itemA', 'itemB']


for item in classes:
    for scope in ["training", "testing"]:
        os.mkdir(os.path.join(DIR, scope, item))

Also make sure that the parent directories (e.g. D:\My\Directory\training) exist before trying to create subdirectories, or use os.mkdirs instead of os.mkdir (see also this question).

CherryDT
  • 25,571
  • 5
  • 49
  • 74
  • Thank You! Worked like a charm! Just for clarification: is there a better way than to use `os.mkdir(os.path.join(DIR, 'train'))` for both train and test, and then having to loop? – Jamie Dimon May 15 '20 at 01:49
  • You mean for creating the parent and the child? Yes, you can use `os.mkdirs`: https://www.geeksforgeeks.org/python-os-makedirs-method/ – CherryDT May 15 '20 at 02:41