lena
lena

Reputation: 727

Putting the name of new created folder in the path of csv file

I am trying to create new csv file in the new created folder, i am asking how can i put the name of new created folder in the path of the csv file

   import os  
   def creat(i,ii):   
   # Directory  
   directory = "NEW"+str(i) 
   # Parent Directory path  
   parent_dir = 'C:\\Users\\lap\\Desktop\\parfolder\\'
   path = os.path.join(parent_dir, directory )   
   os.mkdir(path)  
   print("Directory '% s' created" % directory)  
   with open('C:\\Users\\lap\\Desktop\\parfolder\\%s\\MM%s.csv' %directory 
             %ii , 'w') as file:
        for i in range(1,10):
            file.write("{}\n".format(i))
for i in range(1,4):
   creat(i,i)

Upvotes: 3

Views: 55

Answers (1)

mechanical_meat
mechanical_meat

Reputation: 169284

Based on your error you can wrap the os.mkdir(path) call in a try, except construct:

try:
    os.mkdir(path)
except FileExistsError:
    pass

Edit:
Now you changed the code so you'll have to change this, too:

with open('C:\\Users\\lap\\Desktop\\parfolder\\%s\\MM%s.csv' % (directory,  
          i), 'w') as file:

Upvotes: 2

Related Questions