Parsing a tab delimited file into separate lists or strings

user972297 picture user972297 · Sep 30, 2011 · Viewed 63.3k times · Source

I am trying to take a tab delimited file with two columns, Name and Age, which reads in as this:

'Name\tAge\nMark\t32\nMatt\t29\nJohn\t67\nJason\t45\nMatt\t12\nFrank\t11\nFrank\t34\nFrank\t65\nFrank\t78\n'

And simply create two lists, one with names (called names, without heading) and one with the ages (called ages, but without ages in the list).

Answer

unutbu picture unutbu · Sep 30, 2011

Using the csv module, you might do something like this:

import csv

names=[]
ages=[]
with open('data.csv','r') as f:
    next(f) # skip headings
    reader=csv.reader(f,delimiter='\t')
    for name,age in reader:
        names.append(name)
        ages.append(age) 

print(names)
# ('Mark', 'Matt', 'John', 'Jason', 'Matt', 'Frank', 'Frank', 'Frank', 'Frank')
print(ages)
# ('32', '29', '67', '45', '12', '11', '34', '65', '78')