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 ?
CodePudding user response:
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)