Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Insert a number in string - Python
Next article icon

How to Add Numbers in a Csv File Using Python

Last Updated : 04 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

When working with CSV files in Python, adding numbers in the CSV file is a common requirement. This article will guide you through the process of adding numbers within a CSV file. Whether you're new to data analysis or an experienced practitioner, understanding this skill is vital for efficient data management

CSV (Comma-Separated Values): A common file format for storing tabular data in plain text format, where each line represents a row, and values within a row are separated by commas.

Add Numbers in a CSV File Using Python

Below are the code examples of how to add numbers in a CSV file in Python:

Example 1: Add Values of All Columns of the CSV File

The file structure consists of two files: "main.py" and "numbers.csv".

numbers.csv

A,B
1,2
3,4
5,6

In this example, below code reads a CSV file called "numbers.csv", adds the values from two columns, and saves the results to a new CSV file called "numbers_updated.csv". It iterates through each row of the data, extracts values from columns A and B, performs addition, handles non-numeric values, and writes the updated data back to the new CSV file.

main.py

Python3
import csv  # Step 1: Read the CSV File with open('numbers.csv', 'r') as file:     reader = csv.reader(file)     data = list(reader)  # Step 2: Perform Addition Operation for row in data:     try:         a = int(row[0])         b = int(row[1])         row.append(a + b)     except ValueError:         row.append('')  # Step 3: Write Back to CSV File with open('numbers_updated.csv', 'w', newline='') as file:     writer = csv.writer(file)     writer.writerows(data)  print("Addition completed and updated CSV file created successfully.") 

Output

Addition completed and updated CSV file created successfully.

numbers_updated.csv

A,B,
1,2,3
3,4,7
5,6,11

Example 2: Add Values of Specific Column of CSV file

The file structure consists of two files: "main.py" and "input.csv".

input.csv

Name, Age, Score
John, 25, 85.5
Amy, 31, 92.2
Sam, 28, 78.9

In below example, we are using csv.reader to read the CSV file (eg. input.csv) and store its contents into a suitable data structure, such as a list of lists or a Pandas DataFrame. Then, Iterate over the data and sum up the numbers using the Decimal class for precision. Assuming the numbers are in a specific column, we can access that column by its index.

Python3
import csv from decimal import Decimal, InvalidOperation  # Reads the CSV file and returns the data as a list of rows. def read_csv_file(file_name):     data = []     with open(file_name, 'r') as file:         csv_reader = csv.reader(file)         for row in csv_reader:             data.append(row)     return data  # Iterates over the data and calculates the sum of numbers in a specific column. def sum_numbers(data, column_index):     total = Decimal(0)     for row in data:         try:             number = Decimal(row[column_index])             total += number         except (ValueError, InvalidOperation):             print(f"Invalid value in row: {row}")     return total  # Writes the total to a new CSV file. def write_total_to_csv(total, output_file):     with open(output_file, 'w', newline='') as file:         csv_writer = csv.writer(file)         csv_writer.writerow(['Total'])         csv_writer.writerow([total])         print(f"Total: {total}")  # Displays the total on the console. def display_total(total):     print(f"Total: {total}")  # Driver's code data = read_csv_file('input.csv')  # Adjust the column index according to CSV file total = sum_numbers(data, column_index=2)  # Output the total to a new CSV file write_total_to_csv(total, 'output.csv') 

Output

Invalid value in row: ['Name', ' Age', ' Score']
Total: 256.6

output.csv

Total
256.6

Next Article
Insert a number in string - Python
author
susobhanakhuli19
Improve
Article Tags :
  • Python
  • Python Programs
  • python-csv
Practice Tags :
  • python

Similar Reads

  • How To Create A Csv File Using Python
    CSV stands for comma-separated values, it is a type of text file where information is separated by commas (or any other delimiter), they are commonly used in databases and spreadsheets to store information in an organized manner. In this article, we will see how we can create a CSV file using Python
    3 min read
  • How to Add Two Numbers in Python
    The task of adding two numbers in Python involves taking two input values and computing their sum using various techniques . For example, if a = 5 and b = 7 then after addition, the result will be 12. Using the "+" Operator+ operator is the simplest and most direct way to add two numbers . It perfor
    5 min read
  • How to Add Floats to a List in Python
    Adding floats to a list in Python is simple and can be done in several ways. The easiest way to add a float to a list is by using the append() method. This method adds a single value to the end of the list. [GFGTABS] Python a = [1.2, 3.4, 5.6] #Add a float value (7.8) to the end of the list a.append
    2 min read
  • How to Append Data in Excel Using Python
    We are given an Excel file and our task is to append the data into this excel file using Python. In this article, we'll explore different approaches to append data to an Excel file using Python. Append Data in Excel Using PythonBelow, are some examples to understand how to append data in excel using
    2 min read
  • Insert a number in string - Python
    We are given a string and a number, and our task is to insert the number into the string. This can be useful when generating dynamic messages, formatting output, or constructing data strings. For example, if we have a number like 42 and a string like "The number is", then the output will be "The num
    2 min read
  • How to Take Array Input in Python Using NumPy
    NumPy is a powerful library in Python used for numerical computing. It provides an efficient way to work with arrays making operations on large datasets faster and easier. To take input for arrays in NumPy, you can use numpy.array. Taking Array Input Using numpy.array()The most simple way to create
    3 min read
  • Calculate Average for Each Row in a CSV file using Python
    Working with CSV files is a common task in data analysis and manipulation. Finding the average of each row in a CSV file becomes crucial when dealing with datasets. In this guide, we'll explore how to achieve this using Python, providing a step-by-step approach and practical examples. dataset.csv to
    5 min read
  • Python - Retain Numbers in String
    Retaining numbers in a string involves extracting only the numeric characters while ignoring non-numeric ones. Using List Comprehensionlist comprehension can efficiently iterate through each character in the string, check if it is a digit using the isdigit() method and join the digits together to fo
    2 min read
  • How to Load a File into the Python Console
    Loading files into the Python console is a fundamental skill for any Python programmer, enabling the manipulation and analysis of diverse data formats. In this article, we'll explore how to load four common file types—text, JSON, CSV, and HTML—into the Python console. Whether you're dealing with raw
    4 min read
  • Exporting Multiple Sheets As Csv Using Python
    In data processing and analysis, spreadsheets are a common format for storing and manipulating data. However, when working with large datasets or conducting complex analyses, it's often necessary to export data from multiple sheets into a more versatile format. CSV (Comma-Separated Values) files are
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences