Martynas Šidlauskas
Martynas Šidlauskas

Reputation: 11

Python: How to remove quotes when I add csv data to the list and print it

I am facing a little problem here when I open csv file. I get the CSV data and put it in the list. Once I print the list it populates the data I need + I get the following empty brackets: ['', '', '']:

[['1', '2', 'white'], ['2', '4', 'black'], ['2', '5', 'black'], 
 ['2', '5', 'black'], ['1', '4', 'white'], ['', '', ''], ['', '', ''] etc..

How to get rid of the additional ['', '', ''] part?

Here is my code, sorry I am quite new to this and I could not find the answer on the web:

import math
import csv


class CylinderFactory:

    def __init__(self,filename):

        self.filename = filename
        self.mylist=[]
        self.height = []
        self.diameter=[]

        with open(self.filename, "r") as f:
            reader = csv.reader(f, delimiter=",")
            for row in reader:
                self.mylist.append(row)
                self.height.append(row[0])
                self.diameter.append(row[1])

def main():

   new=CylinderFactory("testfile.csv")
   print(new.mylist)
   print(new.height)

main()

Upvotes: 1

Views: 84

Answers (1)

Alex Hall
Alex Hall

Reputation: 36043

You can just avoid processing such lines, e.g.

for row in reader:
    if row == ['', '', '']:
        continue
    self.mylist.append(row)
    ...

A nice more general condition would be:

    if not any(row):

or if you want to avoid rows that have any empty values, e.g. [['1', '2', '']:

    if not all(row):

Upvotes: 2

Related Questions