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:

Output: 15000

Example 2:

Input: CSV file content:

"Jane",30,"Five Thousand"

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):
        with open(file_name, 'r') as file:
            reader = csv.reader(file)
            next(reader)  # Skip header
            sum = 0
            for row in reader:
                    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


Unlock AI & Data Science treasures. Log in!