Reputation: 509
I am trying to create folders using os.mkdir with looping over a list for example i want 12 folders with names of months, January, February ...etc.
import os
months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
for month in months:
os.mkdir('D:\\Python_GIS')
with many lines like this i could create the folders i wanted
import os
os.mkdir('D:\\Python_GIS\\Jan')
os.mkdir('D:\\Python_GIS\\Feb')
os.mkdir('D:\\Python_GIS\\Mar')
os.mkdir('D:\\Python_GIS\\Apr')
os.mkdir('D:\\Python_GIS\\May')
os.mkdir('D:\\Python_GIS\\Jun')
os.mkdir('D:\\Python_GIS\\July')
os.mkdir('D:\\Python_GIS\\Aug')
os.mkdir('D:\\Python_GIS\\Sep')
os.mkdir('D:\\Python_GIS\\Oct')
os.mkdir('D:\\Python_GIS\\Nov')
os.mkdir('D:\\Python_GIS\\Dec')
But is there any way to do it with looping.
Thanks
Upvotes: 0
Views: 3922
Reputation: 107287
You can use format
:
for month in months:
os.mkdir('D:\\Python_GIS\\{}'.format(month))
Upvotes: 1
Reputation: 5514
This is a prime job for os.path.join()
which joins its arguments by the system's separator. Its also a great way to cut down on \
related errors.
baseDir = "D:\\Python_GIS"
for month in months:
os.makedir(os.path.join(baseDir,month))
Unrelated style note: Try setting your paths as raw strings which will ignore literals, so baseDir = r'D:\Python_GIS'
Upvotes: 7