Home > Net >  Python creating a list from csv file
Python creating a list from csv file

Time:05-25

I want to import csv file that consist of country names to python. Csv file example:

Afghanistan
Albania
Algeria

I tried using these two pieces of code:

import pandas as pd

df = pd.read_csv('COUNTRIES_LIST.csv')
country_list = df.values.tolist()
print(country_list)

and

import csv

with open('file.csv', newline='') as f:
    reader = csv.reader(f)
    country_list = list(reader)

print(country_list)

Both of these give me a list, but the list has square brackets around each value like this:

[['Afghanistan'], ['Albania'], ['Algeria']]

This doesn't work for me because i'd need to change the values of the list to dictionaries, and for some reason the code that im using only works if there are no brackets in the values.

Is there a way to either import the list without the brackets or delete the brackets from the list? Also, if it's not practical to do that what kind file should i use in place of csv? Thanks!

CodePudding user response:

The reason the first code giving you this list of list output because there is only one column in that CSV file and you are not selecting any specific column

Try this -

import pandas as pd

df = pd.read_csv('COUNTRIES_LIST.csv')
country_list = df.iloc[:, 0].values.tolist()
print(country_list)

CodePudding user response:

#read list of countries from file and store in python list

def readCountries(filename):
    countries = []
    with open(filename) as f:
        for line in f:
            countries.append(line.strip())
    return countries



print(readCountries("COUNTRIES_LIST.csv"))

CodePudding user response:

Since your data has just one column, you can squeeze the dataframe to a list before calling tolist:

country_list = df.squeeze().tolist()
  • Related