0

I am trying to fetch last record of csv file using below code.

Nothing gets printed as an output.

I have 101 records in csv file. Need to fetch last record of file

Code :

import csv

count = 0
with open('/folder/emp.csv','r') as csvdt:

  csv_rd = csv.reader(csvdt)
  get_record_count  = len(list(csv_rd)) #101

  for j in  csv_rd:
    if count == get_record_count:
      print(j)
    else:
      count = count + 1

What is internally happening which does not let me print output ?

codeholic24
  • 955
  • 4
  • 22
  • 1
    Maybe the `count` never reaches 101. Loop ends before it. Try printing count in every iteration to see it's max value and what happens when it reaches 101. – Ahmad Anis Mar 13 '22 at 07:58
  • 1
    I think `csv_rd` is a generator and you exhausted it at the line including `len(list(csv_rd))`. – quasi-human Mar 13 '22 at 08:08

1 Answers1

1

csv_rd is a generator, so you exhaust the content of csv_rd if you apply len(list(csv_rd)). In order to prevent exhaustion, you have to get the list of csv_rd first.

Code:

import csv

with open('/folder/emp.csv','r') as csvdt:

    csv_rd = csv.reader(csvdt)

    lines = list(csv_rd)
    get_record_count = len(lines) #101

    for i, line in enumerate(lines, 1):
        if i == get_record_count:
            print(line)

If what you want to do is only getting the last line, the following code might be usefull as well.

import csv

with open('/folder/emp.csv','r') as csvdt:
    csv_rd = csv.reader(csvdt)
    last_line = list(csv_rd)[-1]
    print(last_line)
quasi-human
  • 1,898
  • 1
  • 2
  • 13
  • : can you tell me what is the meaning of exhaustion – codeholic24 Mar 13 '22 at 08:30
  • 1
    Sure. `csv_rd` contained information of the 101 lines at first. Once you called `list(len(csv_rd))`, all the lines were consumed. You can confirm this by a toy example `g = (i for i in range(3)); print(len(list(g))); print(len(list(g)))`. The first `print(len(list(g)))` shows `3`, whereas the second `print(len(list(g)))` shows `0` because of the exhaustion. – quasi-human Mar 13 '22 at 08:34
  • I think this post might be helpful to understand the generator: https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do/231855#231855 – quasi-human Mar 13 '22 at 08:38
  • 1
    When you read something from a file or stream once, you can't read the same thing again (unless the thing you're reading from allows you to explicitly rewind, or gives you the same contents if you close and open it again, which you can do with a file, but not e.g. with a network connection). – tripleee Mar 13 '22 at 08:42
  • @quasi-human : How you are able to debug this from my code. – codeholic24 Mar 13 '22 at 09:04