Sum of the Third Column in a CSV File

Write a Python program that reads a CSV file and prints the sum of the numbers in the third column. The program should handle exceptions for scenarios like a missing file, missing columns, or non-numeric values in the third column.

Example 1:

Input: CSV file content:

"Name","Age","Salary"
"John",25,4000
"Jane",30,5000
"Mike",28,6000
Output: 15000

Example 2:

Input: CSV file content:

"Name","Age","Salary"
"John",25,4000
"Jane",30,"Five Thousand"
"Mike",28,6000

Output: Exception: Non-numeric value in the third column

Use Python’s built-in csv module to read the CSV file. For handling exceptions, use try-except blocks.

import csv

def sum_third_column(file_name):
    try:
        with open(file_name, 'r') as file:
            reader = csv.reader(file)
            next(reader)  # Skip header
            sum = 0
            for row in reader:
                try:
                    sum += int(row[2])
                except ValueError:
                    return "Exception: Non-numeric value in the third column"
            return sum
    except FileNotFoundError:
        return "Exception: File not found"
    except IndexError:
        return "Exception: Less than three columns in the file"

 

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!