Search code examples
pythonstringlistdirectorysubdirectory

Python: Code is not picking up all string values in list


I created the following code to create a number of folders

import os

Country = {"Albania - AL",
"Armenia - AM",
"Austria - AT",
"Bahrain - BH",
"Belarus - BY",
"Belgium - BE",
"Bulgaria - BG",
"Canary Islands - KY",
"Croatia - HR",
"Cyprus - CY",
"Czech Republic - CZ",
"Denmark - DK",
"Estonia - EE",
"Finland - FI",
"France - FR",
"Germany - DE",
"Greece - GR",
"Hungary - HU",
"Iceland - IS",
"Ireland - IE",
"Israel - IL",
"Italy - IT",
"Latvia - LV",
"Lithuania - LT",
"Luxembourg - LU",
"Malta - MT",
"Morocco - MA",
"Netherlands - NL",
"Norway - NO",
"Poland - PL",
"Portugal - PT",
"Romania - RO",
"Russian Federation - RU",
"Saudi Arabia - SA",
"Serbia - RS",
"Slovakia - SK",
"Slovenia - SI",
"South Africa - ZA",
"Spain - ES",
"Sweden - SW",
"Switzerland - CH",
"Turkey - TR",
"United Arab Emirates - AE",
"United Kingdom Of Great Britain And Northern Ireland - UK",
}

for x in Country:
    path = ("C:/Users/thrnma/Documents/VAT Reporting/" + x)

try:
    os.mkdir(path)
except OSError:
    print ("Creation of the directory %s failed" % path)
else:
    print ("Successfully created the directory %s " % path)

When I run the program, it only generates one folder for Saudi Arabia. I tried running it multiple times, but it will not generate any new folders. I assume I need to do something like loop it through, but I am not sure how to do it (still a novice at Python). Thank you in advance.


Solution

  • You didn't put the "creating directory" part in your loop.
    This should work, try to understand the difference:

    import os
    
    Country = {"Albania - AL",
    "Armenia - AM",
    "Austria - AT",
    "Bahrain - BH",
    "Belarus - BY",
    "Belgium - BE",
    "Bulgaria - BG",
    "Canary Islands - KY",
    "Croatia - HR",
    "Cyprus - CY",
    "Czech Republic - CZ",
    "Denmark - DK",
    "Estonia - EE",
    "Finland - FI",
    "France - FR",
    "Germany - DE",
    "Greece - GR",
    "Hungary - HU",
    "Iceland - IS",
    "Ireland - IE",
    "Israel - IL",
    "Italy - IT",
    "Latvia - LV",
    "Lithuania - LT",
    "Luxembourg - LU",
    "Malta - MT",
    "Morocco - MA",
    "Netherlands - NL",
    "Norway - NO",
    "Poland - PL",
    "Portugal - PT",
    "Romania - RO",
    "Russian Federation - RU",
    "Saudi Arabia - SA",
    "Serbia - RS",
    "Slovakia - SK",
    "Slovenia - SI",
    "South Africa - ZA",
    "Spain - ES",
    "Sweden - SW",
    "Switzerland - CH",
    "Turkey - TR",
    "United Arab Emirates - AE",
    "United Kingdom Of Great Britain And Northern Ireland - UK",
    }
    
    for x in Country:
        path = ("C:/Users/thrnma/Documents/VAT Reporting/" + x)
    
        try:
            os.mkdir(path)
        except OSError:
            print ("Creation of the directory %s failed" % path)
        else:
            print ("Successfully created the directory %s " % path)