Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python CSV read a single column as a list

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]))

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading