How to make a list of a csv file

Viewed 34

I have a file (tab delimited) which looks like this:

1    2    3    4    5   
a,f  f,g  g    g    f
df   d,a  a,a  l    ll
dd   ff   g,g  ll   ff
pp   ff   a    ll   pp

Now I want to make a list of the values under the 3th column.

This is my code:

my_list = []
with open(my_file, 'r') as my_table:
    mt_reader = csv.reader(my_table, delimiter = '\t')
    for row in mt_reader:
        my_list.append(row[2])
print(my_list)

This is my outcome:

my_list = ['g', 'a,a', 'g,g', 'a']

This is my expected outcome:

my_list = ['g', 'a', 'a', 'g', 'g', 'a']
2 Answers

You can do it by changing:

my_list.append(row[2])

to

my_list.extend(row[2].split(','))

If you want to do it after reading in your file the way you did, you could use ",".join(my_list) to first join your items together into a single string ("g,a,a,g,g,a") and then use my_list.split(",") to take them apart again:

>>> single_str = ",".join(my_list)
# 'g,a,a,g,g,a'

>>> single_str.split(",")
# ['g', ' a', 'a', ' g', 'g', ' a']

Or at once:

",".join(my_list).split(",")
Related