Search code examples
pythondirectory

How can I create the same multiple folders in many Folders?


I have several folders. For each of these folders, I want to create 4 folders (the same 4 folders in all the other folders).

Here is the Python code I used, but it doesn't work:

import os

listOfIds = [101,102,103,104,105,106,107,108,109,201,202,203,204,205,207,209,212,213,214,219,220,221,222,223,225,227,228,231,232,233,234,236,237,239,240,241,242,245,247,249,252,301,302,303,304,305,306,307,401,402,403,404,406,408,409,410,412,413,414,416,418,419,420,421,422,423,427,428,429,431,433,434,435,436,437,438,439,440,441,501,503,505,506,508,509,510,511,512,514,516,517,520,522,524,526,527,529,601,602,603,605,606,607,608,609,610,611,613,614,616,617,618,621,623,624,627,629,630,631,632,633,634,635,637,638,640,642,644,645,649,650,651,652,653,654,655,657,658,661,701,806,807,808,811,812,813,817,818,821,822,823,824,825,826,827,828,2003,2008,2010,2011,2012,2013,2014,2017,2019]
folders = ['Financial Statement','Corporate Profit','News']

root_path = 'F:/alkhaleej_pdf/BoursaKuwait_Pdfs/'+str(id)

for id in listOfIds:
    for folder in folders:
        path = os.path.join(root_path, folder) 
        os.mkdir(folder)

listOfIds is an array which contains the names of all the folders; folders, instead, contains the name of the folders that I need to create in all the elements of listOfIds.

When I run this code, I get the following error :

FileExistsError: [WinError 183] Unable to create an already existing file: 'Financial Statement'

While the listOfIds folders are empty.


Solution

  • Move the line that generates root_path using id into the loop that cycles through the listOfIds. Also add mkdir for that path:

    import os
    
    listOfIds = [101,102,103,104,105,106,107,108,109,201,202,203,204,205,207,209,212,213,214,219,220,221,222,223,225,227,228,231,232,233,234,236,237,239,240,241,242,245,247,249,252,301,302,303,304,305,306,307,401,402,403,404,406,408,409,410,412,413,414,416,418,419,420,421,422,423,427,428,429,431,433,434,435,436,437,438,439,440,441,501,503,505,506,508,509,510,511,512,514,516,517,520,522,524,526,527,529,601,602,603,605,606,607,608,609,610,611,613,614,616,617,618,621,623,624,627,629,630,631,632,633,634,635,637,638,640,642,644,645,649,650,651,652,653,654,655,657,658,661,701,806,807,808,811,812,813,817,818,821,822,823,824,825,826,827,828,2003,2008,2010,2011,2012,2013,2014,2017,2019]
    folders = ['Financial Statement','Corporate Profit','News']
    
    
    for id in listOfIds:
        root_path = 'F:/alkhaleej_pdf/BoursaKuwait_Pdfs/' + str(id)
        os.mkdir(root_path)
        for folder in folders:
            path = os.path.join(root_path, folder) 
            os.mkdir(path)