-1

SO here's the code -

import csv

with open('csv_example_files.csv') as csvfile:
    readCSV = csv.reader(csvfile , delimiter = ',')
    print(readCSV)
    for row in readCSV:
        print(row)

And the output is:

<_csv.reader object at 0x0000024D3DC42388>
['1/2/2014', '4', 'red']
['1/2/2014', '1', 'kv']
['1/2/2014', '1', 'jblock']
['1/3/2018', '1', 'kv']
['1/5/2114', '1', 'kv']
[]
[]
[]

I didn't expect the last 3 empty lists I don't know why they occurred so help me out. I am just a beginner and as I was following a tutorial series and I got stuck here.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 1
    Please [edit] your question and add a copy of the `csv_example_files.csv` file you're testing with. Also, in Python 3 you should add a `newline=''` keyword argument to the `open()` call. For Python 2, you need to add a mode argument after the file name argument of `'rb'`. – martineau Jan 04 '18 at 16:16
  • 1
    If your CSV file contains blank lines, you could add `if len(row) == 3:` before your print statement to skip over them. – Martin Evans Jan 04 '18 at 17:57

3 Answers3

2

It is likely that your CSV file ends with 3 newlines. These result in empty lists when reading via csv module.

sophros
  • 14,672
  • 11
  • 46
  • 75
1

You are getting those extra lines as your CSV file contains blank lines. You can either edit the file and remove the blank lines, or alternatively add a test to make sure that the row contains the correct number of cells, e.g. 3:

import csv

with open('csv_example_files.csv', newline='') as f_input:
    csv_input = csv.reader(f_input)

    for row in csv_input:
        if len(row) == 3:
            print(row)

This should give you the following output:

['1/2/2014', '4', 'red']
['1/2/2014', '1', 'kv']
['1/2/2014', '1', 'jblock']
['1/3/2018', '1', 'kv']
['1/5/2114', '1', 'kv']

Note: The delimiter for a CSV file is already a ,. You should also add newline='' when using Python 3.x

Martin Evans
  • 45,791
  • 17
  • 81
  • 97
-1

Try add csvfile.readline():

with open("csv_example_files.csv") as csvfile:
    csvfile.readline()
    readCSV = csv.reader(csvfile , delimiter = ',')
    print(readCSV)
    for row in readCSV:
        print(row)

Check this answers

Gianmar
  • 505
  • 3
  • 13