Search code examples
pythonlistsplitreadfile

Take list of strings and split it based on commas into 2d list


So far I have the the following code:

def display2dlist(data):
    for i in data:               #loops through list
        lines = i.strip()       #removing leading and trailing characters
        split_lines = lines.split(", ")       #splitting lines by ','
        print(split_lines)       #prints list


with open("python.csv", "r") as infile:
    data = infile.readlines()[0:]       #reads lines from file 
#print(data)
display2dlist(data)       #calling the function display2dlist with data list as parameter

It reads lines from a csv file and saves each line as a list. It outputs this:

['2016,London,10']
['2017,Tokyo,11']
['2018,Toronto,12']
['2018,Dubai,23']

How would I make it so instead of saving each line as just one big string. It splits the lines at every comma and saves multiple values. So it should look like this:

['2016','London','10']
['2017','Tokyo','11']
['2018','Toronto','12']
['2018','Dubai','23']

For example in my current code:

data[0][0]= '2'
data[0][1]= '0'        #it is treating it as a big string and just going letter by letter
data[0][2]= '1'
data[1][0]= '2'
data[1][1]= '0'         
data[1][2]= '1'

I want it so when I execute the previous code the output is:

data[0][0]='2016'
date[0][1]='London'
data[0][2]='10'
data[1][0]='2017'
data[1][1]='Tokyo'         
data[1][2]='11'

Solution

  • Remove extra space in split method and use thos function to get nested list:

    def get_2d(data):
        listdata = []
        for i in data:
            split_lines = i.strip().split(",") #  not ", "
            listdata.append(split_lines)
        return listdata
    
    ...
    
    with open("python.csv", "r") as infile:
        data = infile.readlines()[0:] 
    print(get_2d (data))