Python CSV read a single column as a list

Question:

I have this code:

type(i[0]) == 'str'. How can I get it as a list? and later get print(i[0][0]) == 'a'

import csv
i = [['a', 'b'], 'c', 'd']
with open('a.csv', 'a', newline='', encoding='utf-8') as file:
    writer = csv.writer(file, delimiter=';')
    writer.writerow(i)

file.close()
with open('a.csv', 'r', newline='', encoding='utf-8') as file:
    for i in csv.reader(file, delimiter=';'):
        print(type(i[0]))
Asked By: Mhd

||

Answers:

You can use a for-loop. Like this:

example a.csv

hello, aloha, hola
bye, aloha, adios

python code:

import csv


col1 = []
with open('a.csv')  as file:
    r = csv.reader(file)
    for row in r:
        col1.append(row[0])

print(col1)  # => ['hello', 'bye']

Alternatively, you could also use a list comprehension:

import csv


col1 = []
with open('a.csv')  as file:
    r = csv.reader(file)
    col1 = [row[0] for row in r]

print(col1)  # => ['hello', 'bye']
Answered By: Michael M.

The reason it is returning str instead of list because the csv writer will always do the equivalent of str(['a','b']), which is "['a', 'b']",c,d, so you can use ast.literal_eval to get the list from the string list like this for the first element-

import csv
import ast
i = [['a', 'b'], 'c', 'd']
with open('a.csv', 'a', newline='', encoding='utf-8') as file:
    writer = csv.writer(file, delimiter=';')
    writer.writerow(i)

file.close()
with open('a.csv', 'r', newline='', encoding='utf-8') as file:
    for i in csv.reader(file, delimiter=';'):
        i[0] = ast.literal_eval(i[0])
        print(type(i),type(i[0]), i[0][0])
Answered By: Always Sunny
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.