Home > Blockchain >  How to append a row of a CSV as a string (and not individual lists) to a list
How to append a row of a CSV as a string (and not individual lists) to a list

Time:10-12

I have a .csv file with one column (approx 5k rows). I want to convert all this into a list that looks like this:

key_list = ['key_1','key_2','key_3'...]

The 'key_1', 'key_2' etc are individual rows within my csv file.

To do this, I am using the csv module. My code does:

import csv

key_list = []

with open('key_list.csv','r') as file:
    reader = csv.reader(file, delimiter = ',')

    for row in reader:
        key_list.append(row)

However this creates the following output when I go to print(key_list):

[['key_1'],['key_2']]

When I then go to use this in my code, by looping through the list, I am trying to save key_list[0] = 'key_1' as a string, but my code is outputting ['key_1'] as a list and failing.

What do I need to change so I can get a list that looks like:

key_list = ['key_1','key_2','key_3'...]

Thank you

CodePudding user response:

You can unpack the first column from the row:

key_list = [key for key, in reader]

CodePudding user response:

You can also do in one line with map:

import csv
key_list = list(map(lambda row: row[0], csv.reader(open('key_list.csv'))))
print(key_list)

Or list comprehension:

import csv
key_list = [row[0] for row in csv.reader(open('key_list.csv'))]
print(key_list)

CodePudding user response:

When you read the CSV file, each row is going to be treated as a list. so changing each list to a string will give you the key_list = ['key_1','key_2','key_3'...] as key_1, key_2, ... as a string. Try this one,

import csv

key_list = []

with open('snakes_count_10.csv','r') as file:
    reader = csv.reader(file, delimiter = ',')

    for row in reader:
        key_list.append(', '.join(row))

print(key_list)
  • Related