Home > Software design >  i have to display all records with age>30 from csv file, its displaying the records more than 1 t
i have to display all records with age>30 from csv file, its displaying the records more than 1 t

Time:09-17

its displaying the records more than 1 time. how to avoid that

import os

import csv

def dispcond():

    f=open('csv2.csv','r')
    empdata=csv.reader(f)
  
    rec=[]
    l=[]
    for i in empdata:
        rec.append(i)
        for j in range(1,len(rec)):
            print(j)
        
    f.close()
dispcond()

CodePudding user response:

You don't need a list. Your file is already a list of lines.

import csv

def dispcond():

    with open('csv2.csv','r') as f
        empdata=csv.reader(f)
  
        for line in empdata:
            age = int(line[1])  # the second column, for example
            if age > 30:
                print(age)

For CSV data, it is more common to use Pandas

CodePudding user response:

import os
import csv

def dispcond():
    f=open('csv2.csv','r')
    empdata=csv.reader(f)
    rec=[]
for i in empdata:
    rec.append(i)
for j in range(1,len(rec)):
    if int(rec[j][1])>30:
        print(rec[j])
f.close()
dispcond()
  • Related