Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python CSV reading - I think I'm making a list of lists but I just want a list

Tags:

python

csv

This regards Python 2.7

I have a csv file, soq1, that looks like this in Notepad:

csv file in Notepad

I used this code to read in the file and display the contents of the list soq1:

import csv
with open('D:\Users\Richard\Python\soq1.csv','rb') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    soq1=list(readCSV)

print(soq1)
print(type(soq1))
print(len(soq1))

with results of: results

I was expecting soq1 to look like: ['2','3','4','5','6']

In other words, I did not expect to have the extra set of square brackets. Did I create a list of lists?

What did I do wrong?

like image 374
RichardAdams Avatar asked Jan 19 '26 18:01

RichardAdams


2 Answers

You didn't do anything wrong - the csv module just returns one list per line (which makes sense for CSVs with multiple entries in each line.)

You can flatten your list using

soq2 = [elt for lst in soq1 for elt in lst]

Although for such a simple file, you don't really need to handle it as a CSV at all (it doesn't matter what the file extension is.) You could just do:

with open(my_file) as f:
    soq1 = [line.strip() for line in f]
like image 150
perigon Avatar answered Jan 22 '26 08:01

perigon


Yes, you created a list of lists, but this is intentional because by nature, CSV files are meant to have separate entries delimited by new lines, and separate properties in each entry delimited by commas (why they call it comma separated values).

That is not a proper CSV file, by the way. The convention is that the first line (also known as the header line) should denote comma-separated strings describing what each value means in successive lines/entries.

If you would like to read that file and produce ['2','3','4','5','6'], csv.reader is not suited to your specific use case. You will want to read each separate line and append it to a list, or read the entire file in and split it into a list using \n as a delimiter.

like image 31
JoshuaRLi Avatar answered Jan 22 '26 07:01

JoshuaRLi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!