4

I have a following type of csv

a,b,c
1,2,3
4,5,6
7,8,9

I would like to parse every column of this csv file into a list with out columns so the end result would be

myList = ["1","4","7","2","5","8","3","6","9"]

I have found many solutions for one column but i need to be flexible to be able to read every column of the file. I'm using an older version of python so i can't use any solutions with pandas library.

1
  • There is no direct way to do this, you have to loop through each row and add that in single array Commented May 10, 2017 at 18:42

3 Answers 3

5

You could read the file fully and then zip the rows to transpose them, then chain the result to flatten the list. Standalone example (using a list of strings as input):

import csv,itertools

text="""a,b,c
1,2,3
4,5,6
7,8,9
""".splitlines()

myList = list(itertools.chain.from_iterable(zip(*csv.reader(text[1:]))))

print(myList)

result:

['1', '4', '7', '2', '5', '8', '3', '6', '9']

from a file it would read:

with open("test.csv") as f:
    cr = csv.reader(f,separator=",")  # comma is by default, but just in case...
    next(cr)  # skip title
    myList = list(itertools.chain.from_iterable(zip(*cr)))
Sign up to request clarification or add additional context in comments.

3 Comments

splitlines() was just to create a standalone example. you don't need splitlines for a file. Check my second example where the input is a file. Don't use a DictReader because the order of the values would depend on the order of the keys, which isn't what you want.
Thanks, I tried the code, but i get ['1;2;3', '4;5;6', '7;8;9'], nvm ... excel was screwing me over ... it added a ';' instead of ','
that's because your file doesn't match the file you posted. Try adding a separator (see my edit)
0

Simple approach:

d = """a,b,c
1,2,3
4,5,6
7,8,9
"""

cells = []
for line in d.split("\n"):
    if line:
        cells.append(line.strip().split(','))

print(cells)

for n in range(len(cells[0])):
    for r in cells:
        print(r[n]) 

Same iteration, but as generator:

def mix(t):
    for n in range(len(t[0])):
        for r in t:
            yield r[n]

print( list( mix(cells) )  )

Comments

0

Using csv and chain to flatten the list

import csv
from itertools import chain

l = list(csv.reader(open('text.csv', 'r')))
mylist = map(list, zip(*l[1:])) # transpose list
list(chain.from_iterable(mylist)) # output ['1', '4', '7', '2', '5', '8', '3', '6', '9']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.