1

I am writing a script in python to read a .csv file and print it on the basis of row.I am not getting any error while executing, but it doesn't get printed. The code is as follows.

import os
import csv

os.chdir('C:\ingenium')

exampleFile = open('testt.csv')
exampleReader = csv.reader(exampleFile)
exampleData = list(exampleReader)
for row in exampleReader:
    print (row)
exampleFile.close()

Later I have found out that the word "row" doesnt have any significance in code as I replace "row" by any random string (for eg:"gcgc") it doesnt show any error. . I am using Pycharm as IDE.

3 Answers3

4

Your bug is here:

exampleData = list(exampleReader)

You already exhausted the generator object exampleReader, so you don't get anything when you iterate over it.

You should iterate over the new list instead:

for row in exampleData:
    print(row)
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
0

Try this:

import os

import csv

os.chdir('C:\ingenium')

exampleFile = open('testt.csv','r')
exampleReader = csv.reader(exampleFile)
for row in exampleReader:
    print (row)
exampleFile.close()

As moses said, you already exhausted the csv.reader by importing the csv to list.

Wajahat
  • 1,593
  • 3
  • 20
  • 47
0

Given the specific task, printing the lines, it might be worth playing with simpler file handling.

import os
os.chdir('C:\ingenium')

lines = open('testt.csv','r').readlines()
for line in lines:
    print (line)
pcurtain
  • 1
  • 1
  • Even if your solution works the OP is asking why they solution not work. Could you shed some light on that? – yeiniel Jun 24 '16 at 16:34
  • Sure! Think of an iterator as the arm on a turntable. It starts at the outside (first track) and works it's way thru to the center (end of the album). When it gets there, it's **done**. When his code begins the for loop, the 'reader' is empty (finished). – pcurtain Jul 06 '16 at 21:27
  • Also, that for loop would have explained itself to the OP if he added one more print statement, something like: for row in example reader: print '- ', row – pcurtain Jul 06 '16 at 21:29