qeia qeia - 18 days ago 5
Python Question

Read csv file into list of lists without string convertion in Python

I have got a car.csv, which has lines like this:

vhigh,vhigh,2,2,small,low,unacc


I want to get:

[vhigh,vhigh,2,2,small,low,unacc].


But with this code

import csv
a = []
with open("car.csv", 'r') as f:
reader = csv.reader(f)
for line in f:
a.append([line]);


I get

['vhigh,vhigh,2,2,small,med,unacc\n'].


Can someone help me?

Answer

When you create the reader, iterate over that instead of over the file so do:

for line in reader:
    a.append(line)

or if you just want all the lines as a list

a = list(reader)

putting that all together:

with open("car.csv", "r") as f:
    reader = csv.reader(f)
    a = list(reader)