-1

I am fairly new to coding, and I need to put columns from a CSV file into a list. I cannot use any libraries like Pandas. This is the current code I have, but it is taking each character individually. What do I need to change so it takes the entire word?

def readfile(f):
    with open(f) as csv_file:
        csv_reader= csv.reader(csv_file, delimiter= ',')
        
        for i in csv_reader:
            newlist= list(i[1])
            print(newlist)

This is an example of the output created.

['P', 'O', 'P', 'U', 'L', 'A', 'T', 'I', 'O', 'N']
['5', '2', '2', ',', '8', '1', '8']
['1', '5', '5', ',', '6', '5', '6']
['9', '6', '6', ',', '7', '0', '9']
['7', '7', '3', ',', '8', '8', '7']
['8', ',', '4', '4', '7', ',', '6', '0', '9']
['1', '4', ',', '4', '8', '4', ',', '2', '4', '2']
['1', ',', '3', '6', '4', ',', '4', '0', '0']
['1', ',', '1', '7', '1', ',', '0', '2', '7']
['4', ',', '3', '5', '0', ',', '9', '0', '1']
['5', ',', '0', '4', '6', ',', '7', '8', '0']
['4', '0', ',', '6', '0', '1']
['4', '4', ',', '9', '0', '9']
['3', '8', ',', '6', '6', '6']

I need it to all be in one list, like [522,818 , 155,656 , etc]

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
  • Do not do `list(i[1])`. You convert a string into a list of letters. – DYZ Sep 21 '20 at 21:47
  • Are you saying that you'd like to concatenate the outputs of all rows into one list? For example, you have two rows (row 1: [1,2]) and (row 2: [3,4]). You want to produce a list containing [1,2,3,4]? – dmlicht Sep 21 '20 at 22:10
  • 2
    Post the first 10 lines of your CSV file. – darcamo Sep 21 '20 at 22:24

2 Answers2

0

Assuming you would like to concatenate the rows from a csv containing a list in each row, such that an input csv looking like:

population
1,2
3,4

would print -> [1,2,3,4]

You can use the extend function on the python list builtin. Here's how it would look:

import csv
with open('example.csv') as ff:
     reader = csv.reader(ff)
     reader.next() # skip the header that you arent using
     concat_output = []
     for row in reader:
         concat_output.extend(row)
     print(concat_output)
dmlicht
  • 2,328
  • 2
  • 15
  • 16
0

Perhaps this is what you are looking for:

>>>''.join(['5', '2', '2', ',', '8', '1', '8'])
'522,818'

I just found this earlier thread which provides more background/terminology: How to concatenate items in a list to a single string?.

Robert_RP
  • 55
  • 5