loop in python to create folders: "The system cannot find the path specified"

I am using os.path.join and os.mkdir to create folders on a loop.I would like to create a folder with the city name/inputs/b-d.

However, returns error. Similar behavior to this:

import shutil, os
PATH_TEST=r'C:\Users\Ricardo\Dropbox\test'

d = {'Municipalities': ['NY', 'Boston']}
df = pd.DataFrame(data=d)
df
for index in range(len(df)):
    aaa = os.path.join(PATH_TEST,df['Municipalities'][index],'inputs',"b-d")
    if not os.path.exists(aaa):
        os.mkdir(aaa)

Error:

FileNotFoundError                         Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_23524\2121887104.py in <cell line: 6>()
      7     aaa = os.path.join(PATH_TEST,df['Municipalities'][index],'inputs',"b-d")
      8     if not os.path.exists(aaa):
----> 9         os.mkdir(aaa)

FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\\Users\\Ricardo\\Dropbox\\test\\NY\\inputs\\b-d'

>Solution :

I would need to see your file system to answer fully but it seems likely that you’re trying to create multiple folders e.g. NY, inputs and b-d which os.mkdir will not handle.

Instead I recommend swapping out os.mkdir with os.makedirs.

Leave a Reply