grapestory
grapestory

Reputation: 183

Read csv of ints into single list in Python

I have a csv of integers and I want to read them all into one list in Python. How exactly can I do that?

I have searched a bunch on here and every piece of code I tried would output a row of integers as a list and thus creates a list of lists.

Ideally I am looking for something like this as an output: [2,4,6,6,4,6,4,12,12,4] but I keep getting this: [[2,4,6,6,4,'',],[6,4,12,12,4,'',],...]

Here is a snippet of the csv: enter image description here

Upvotes: 2

Views: 1506

Answers (2)

marsnebulasoup
marsnebulasoup

Reputation: 2660

I think this will work for you:

import csv

path = 'text.csv'                #change to path of your csv file
thelist = []                     #define new list

with open(path, 'r') as csvfile: #open csv file
    reader = csv.reader(csvfile) #read it
    for row in reader:           #iterate through each row 
        for item in row:         #iterate through each item of that row
            thelist.append(int(item)) #convert item to an int and add it to thelist


print(thelist)                   #print it

Note that all the items in the csv file must be integers for this to work, or it will throw an error. You can change int(item) to item to just get a list of strings

text.csv:

1,2,3,4,5,6
7,8,9,0,1,2
3,4,5,6,7,8
4,5,6,7,8,9

OUTPUT:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 4, 5, 6, 7, 8, 9]

Bonus, probably useless, one-liners (without the csv module):

With list comprehension:

thelist = [int(item) for item in open('text.csv').read().replace('\n', ',').split(',')]

...or, with map:

thelist = list(map(int, open('text.csv').read().replace('\n', ',').split(',')))

...or with with, which automatically closes the file after using it:

with open('text.csv') as f: thelist = list(map(int, f.read().replace('\n',',').split(',')))

Run and edit these one-liners online

Upvotes: 1

Use list.extend() to add cell items to the list:

enter image description here

import csv 

with open('data.csv', 'r') as csvfile:
    mylist = []
    for row in csv.reader(csvfile, delimiter=','):
        mylist.extend(map(int,row))

>>> print(mylist)
[2, 4, 6, 6, 4, 6, 4, 12, 12, 4]

Upvotes: 1

Related Questions