KnowledgeBoat Logo

Computer Science

A csv file "Happiness.csv" contains the data of a survey. Each record of the file contains the following data:

  • Name of a country
  • Population of the country
  • Sample Size (Number of persons who participated in the survey in that country)
  • Happy (Number of persons who accepted that they were Happy)

For example, a sample record of the file may be:

[‘Signiland’, 5673000, 5000, 3426]

Write the following Python functions to perform the specified operations on this file:

(I) Read all the data from the file in the form of a list and display all those records for which the population is more than 5000000.

(II) Count the number of records in the file.

Python File Handling

3 Likes

Answer

Let the "Happiness.csv" file contain the following data:

Signiland, 5673000, 5000, 3426
Happiland, 4500000, 4000, 3200
Joyland, 8000000, 6000, 5000
Cheerland, 3000000, 3500, 2500

(I)

def show(): 
    file = open("Happiness.csv",'r') 
    records=csv.reader(file) 
    for i in records: 
        if int(i[1])>5000000: 
            print(i) 
    file.close() 
Output
['Signiland', '5673000', '5000', '3426']
['Joyland', '8000000', '6000', '5000']

(II)

def Count_records(): 
    f = open("Happiness.csv",'r') 
    records=csv.reader(f) 
    count=0 
    for i in records: 
            count+=1 
    print(count) 
    f.close() 
Output
4

Answered By

3 Likes


Related Questions