Reputation: 5
I'm trying to create a directory structure of years containing sub-directories representing months, ie.
My code is like this:
newpath = "test"
for year in range(2000, 2013):
for month in range(1, 13):
newpath += str(year)+'\\'+str(month)
if not os.path.exists(newpath):
os.makedirs(newpath)
I am getting an error
OSError: [Errno 2] No such file or directory: 'test\\2000\\1
Would someone please have some information on this Thank you
Upvotes: 0
Views: 453
Reputation: 530843
You aren't resetting newpath
inside the loop. Something like this should work better:
for year in range(2000, 2013):
for month in range(1,13):
newpath = os.path.join("test", str(year), "%02d"%(month,)
if not os.path.exists(newpath):
os.makedirs(newpath)
Upvotes: 0
Reputation: 69012
your newpath
will be
test2000\12000\22000\32000\42000\52000\62000\72000\82000\92000\102000\112000\122001\12001\22001\32001\42001\52001\62001\72001\82001\92001\102001\112001\122002\12002\22002\32002\42002\52002\62002\72002\82002\92002\102002\112002\122003\12003\22003\32003\42003\52003\62003\72003\82003\92003\102003\112003\122004\12004\22004\32004\42004\52004\62004\72004\82004\92004\102004\112004\122005\12005\22005\32005\42005\52005\62005\72005\82005\92005\102005\112005\122006\12006\22006\32006\42006\52006\62006\72006\82006\92006\102006\112006\122007\12007\22007\32007\42007\52007\62007\72007\82007\92007\102007\112007\122008\12008\22008\32008\42008\52008\62008\72008\82008\92008\102008\112008\122009\12009\22009\32009\42009\52009\62009\72009\82009\92009\102009\112009\122010\12010\22010\32010\42010\52010\62010\72010\82010\92010\102010\112010\122011\12011\22011\32011\42011\52011\62011\72011\82011\92011\102011\112011\122012\12012\22012\32012\42012\52012\62012\72012\82012\92012\102012\112012\12
in your last iteration. you don't need to append to newpath
.
Upvotes: 0
Reputation: 212825
newpath += str(year)+'\\'+str(month)
appends new characters to one and the same string at every iteration, which is not what you want.
Try this:
root_path = "test"
for year in range(2000, 2013):
for month in range(1, 13):
newpath = os.path.join(root_path, '{0:04}'.format(year), '{0:02}'.format(month))
if not os.path.exists(newpath):
os.makedirs(newpath)
The os.path.join
will build the pathname correctly on your OS.
Upvotes: 1
Reputation: 363487
str(1)
returns 1
, not 01
. Do "%02d" % month
.
(And consider using os.path.join
to build path strings.)
Upvotes: 4