Ash912 T Ash912 T - 14 days ago 5
Python Question

Python - Create multiple folders by reading csv file and also check if folders already exists, if not make a new folder

I want to first read csv file then check if the folders exists, if not create a new one.
I have information from csv file as follows:

enter image description here

After reading csv file it should create program folder then under program folder it game type sub folder then developer sub folder and game char sub folder. The folder structure should look something like this:



  1. A380 / Warcraft / 69 / Blizzard / Strategy

  2. A380 / Overwatch/ 69 / Blizzard / Shooter

  3. A350 / Skyrim / 51 / Bethesda / Role Playing




So there will be multiple folders inside for example warcraft and overwatch will be two folders inside A380 folder.

So far I have done this:



import os
import csv

output_root = r'/myProgram'

#csv_filename = raw_input('Enter CSV filename:')
with open('insurance_sample.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter = ';')
header = next(readCSV)





Please let me know if the question is still confusing and I will try to explain in more detail.

Answer

First you have to extract the values of one row and join them to a path name. Afterwards os.path.exists checks if the directory exists and os.makedirs creates recursively the directories for you.

So you can try this:

import os
import csv

with open('insurance_sample.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter = ';')
    header = readCSV.next()
    for row in readCSV:
        dirname = "/".join((row[0], row[1], row[3], row[4], row[7]))
        if not os.path.exists(dirname):
            os.makedirs(dirname)