-1

Here's what I've tried:

def CreateDict(BDF):
    with open('%sdata\\%s.csv' % (mainDir,BDF), mode='r') as infile:
        reader = csv.reader(infile)
        for row in reader:
            key = row[0]
            print("%s%s = %s" % (BDF,[key],row[1:]))

CreateDict(FileName)

Print gives me the correct answer. However I want to put it inside a dictionary instead of just printing it out. And I want that dictionary to have the name of FileName).

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

1 Answers1

1

To create the dictionary:

def CreateDict(BDF):
    saved={}
    with open('%sdata\\%s.csv' % (mainDir,BDF), mode='r') as infile:
        reader = csv.reader(infile)
        for row in reader:
            key = row[0]
            saved[key]=row[1:]
    return saved

I don't know how to give to the dict a specific name, if you need to save more than one CSV file you can use a dictionary where the keys are the fileNames:

 fileNames=['test0', 'test1', 'test2']
 all_files={}
 for fileName in fileNames:
     all_files[fileName]=CreateDict(fileName)
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Giuseppe Angora
  • 833
  • 1
  • 10
  • 25
  • It doesn't seem to work. I used print('test0') and it says that 'test0' is not defined (I have a csv named test0). – Miguel Alberola Cano Jun 04 '17 at 09:42
  • I'm half-way there. I've tried changing the last line by this: fileName = CreateDict(fileName) – Miguel Alberola Cano Jun 04 '17 at 09:49
  • I don't know how you can give to a variable a "string name", so you can't do: print(test0), becouse test0 was never defined, but you can do: print(all_files['test0']), this should work – Giuseppe Angora Jun 04 '17 at 13:31
  • I've been using that and it works. However is there a way I can automatically define test0, test1 and etc. so I can use it instead all_files['test0'] ? Though I think it's ok to use that, I'd just prefer to be able to use test0 and etc. instead. – Miguel Alberola Cano Jun 04 '17 at 14:19