1

I have this csv file created using writerow function from the csv module. The file has 63 lines. I want to create a list of lists in python from this file.

I tried the following code:

import csv

dataset = []

def importCsv(file):
    x = 0
    print(dataset)
    with open(file, newline='') as csvfile:
        data = csv.reader(csvfile, delimiter=',', quotechar='|')
        for row in data:
            #print(type(row))
            dataset.append(row)
            x += 1
        print(x)

importCsv(csvPath)

But when I try print(len(dataset)), it outputs 126 instead of 63. I am really confused. Why is the number of items in dataset so high?

1 Answers1

1

The problem is mostly due to spurious CarriageReturn \r chars, causing some empty rows to appear. You can skip empty rows by adding an explicit check

    for row in data:
        if row:
            dataset.append(row)
            x += 1
Sunitha
  • 11,777
  • 2
  • 20
  • 23