Hirshy
Hirshy

Reputation: 157

Create folders from csv.file

I want to create several folders with information from a csv file that is given as

Name,GivenName,id
Doe,John,12345
Doe,Jane,23456

For each person/entry one folder should be created where the id is the name of the folder.

I did find a similar problem with a solution here where the accepted answer used python with the following code:

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)

I changed this to

import os
import csv

with open('input.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter = ',')
    header = readCSV.next()
    for row in readCSV:
        dirname = "/".join((row[2]))
        if not os.path.exists(dirname):
            os.makedirs(dirname)

as I only need the entry for id expecting to get one folder named 12345 and one folder named 23456. Instead I get a nested folder 1>2>3>4>5 and another nested folder 2>3>4>5>6.

I am completely new when it comes to python (or programming) so I don't really know why this happened or how to fix this. I am also not set on using python, just anything that works will be fine. I am using Ubuntu 20.04

Upvotes: 0

Views: 1007

Answers (1)

buran
buran

Reputation: 14233

row[2] is string, e.g. '12345'. when you do "/".join((row[2])) dirname is '1/2/3/4/5'. Do just dirname = row[2]} Note that this is relative path, so the dir will be created in the current working directory.

Note that your code is prone to race condition. When you check if folder exists, another process may create/delete it before you try to use it.

Upvotes: 1

Related Questions