Python Forum

Full Version: CSV reader : save the content into a list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I want to read a csv file and save the content in a list call 'data'. The following reads the data but do not save a list with the content.

import csv
with open('file.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter =';')
I believe this is very basic yet I couldn't find the answer after a google search without too advanced coding.
import csv

with open('file.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=';')
    for row in readCSV:
        print(row)
Are you sure the delimiter is a ';' ?
(Oct-18-2017, 10:42 PM)Larz60+ Wrote: [ -> ]
import csv

with open('file.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=';')
    for row in readCSV:
        print(row)
Are you sure the delimiter is a ';' ?

Hmm. My csv file is a multidimensional table (252 rows and 51 columns). When I run that code it only saves the last row. How do I fix that?
I tried this with a csv file and all rows were listed.
Perhaps your file is not truly a csv file?
(Oct-23-2017, 04:55 PM)econmajor Wrote: [ -> ]Hmm. My csv file is a multidimensional table (252 rows and 51 columns). When I run that code it only saves the last row. How do I fix that?

The variable row contains only the current data of iteration step. After leaving the for loop, row contains the last row. If you want to add the data to a list, then add the data to a list.

before you iterating over the rows, you create an empty list and assign it to a name data for example.
data = []
In each iteration step you append the current rot to the list object.

data.append(row)
If you just want to read the whole csv into memory without any processing between, you can have this cheaper.

import csv

with open('file.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=';')
    data = list(readCSV)