Search code examples
pythonparsingcsvreadlines

Parsing with Python


I am attempting to parse a file. Currently, I have this file:

word1 52345325
word2 12312314
word3 7654756
word4 421342342

I am attempting to store word1 word2 word3 and word4 into an array and the numbers adjacent to those words into another array.

So if i say a[0] i should get word1, and if I say b[0] i should get 52345325 and so on.

I was thinking about making a key-valued pair dictionary object but that may be a little complex at this point as I am just getting into python.

I currently am doing this but of course, it ain't working :P

def csvStringParser():
    a = {}
    b = {}
    i = 0
    f = open('/Users/settingj/Desktop/NOxMultiplier.csv')
    for line in f.readlines():
    reader = csv.reader(line.split('\t'), delimiter='\t')
        for row in reader:
            #print '\t'.join(row)                                                                                                                                                                                                                                             
            #print i                                                                                                                                                                                                                                                          
            a[i] = '\t'.join(row)
            b[i] = '\t'.join(row)
            print a[i]
            print b[i]
            i+=1

This is honestly my first hour of using python. I could easily do this in C++ but I'm am currently just trying to learn python to understand it's greater benefits/simplicity over c++.


Solution

  • import csv
    
    a = {}
    with open('/Users/settingj/Desktop/NOxMultiplier.csv') as f:
        reader = csv.reader(f, delimiter='\t')
        for row in reader:
            a[row[0]] = row[1]
    print a
    

    For two arrays:

    a = []
    b = []
    with open('/Users/settingj/Desktop/NOxMultiplier.csv') as f:
        reader = csv.reader(f, delimiter='\t')
        for row in reader:
            a.append(row[0])
            b.append(row[1])
    print a
    print b
    

    of even just similar solution with the zip:

    with open('/Users/settingj/Desktop/NOxMultiplier.csv') as f:
        a, b = zip(*csv.reader(f, delimiter='\t'))
    print a
    print b