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:
How to Read Text File Into List in Python?
Next article icon

How to read numbers in CSV files in Python?

Last Updated : 12 Dec, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Prerequisites: Reading and Writing data in CSV, Creating CSV files 

CSV is a Comma-Separated Values file, which allows plain-text data to be saved in a tabular format. These files are stored in our system with a .csv extension. CSV files differ from other spreadsheet file types (like Microsoft Excel) because we can only have a single sheet in a file, and they cannot save cells, columns, or rows. Also, we cannot save formulas in this format.

To parse CSV files in Python, we make use of the csv library. The CSV library contains objects that are used to read, write and process data from and to CSV files. Let’s see how we can add numbers into our CSV files using csv library.

Steps to read numbers in a CSV file:

  1. Create a python file (example: gfg.py).
  2. Import the csv library.
  3. Create a nested-list 'marks' which stores the student roll numbers and their marks in maths and python in a tabular format.
  4. Open a new csv file (or an existing csv file) in the 'w' mode of the writer object and other necessary parameters (here delimiter & quoting).
  5. Write into it the list 'marks' with the help of writerows method.
  6. In order to read the rows, make use of reader object and store each row(which is also a list) in a new list 'output'.
  7. Print the list output for verifying the code.

Reading numbers in a CSV file without quotes:

In order to write in our CSV file ‘my_csv’,  we make use of the writerows() method of the writer object. But to read numbers as they are, we will make use of an optional parameter of the writer object, which is ‘quoting’. The 'quoting' parameter tells the writer which character is to be quoted.

If quoting is set to csv.QUOTE_NONNUMERIC, then .writerow() will quote all fields which contain text data and convert all numeric fields to the float data type.

Code:

Python3
import csv  # creating a nested list of roll numbers, # subjects and marks scored by each roll number marks = [     ["RollNo", "Maths", "Python"],     [1000, 80, 85],     [2000, 85, 89],     [3000, 82, 90],     [4000, 83, 98],     [5000, 82, 90] ]  # using the open method with 'w' mode # for creating a new csv file 'my_csv' with .csv extension with open('my_csv.csv', 'w', newline = '') as file:     writer = csv.writer(file, quoting = csv.QUOTE_NONNUMERIC,                         delimiter = ' ')     writer.writerows(marks)  # opening the 'my_csv' file to read its contents with open('my_csv.csv', newline = '') as file:        reader = csv.reader(file, quoting = csv.QUOTE_NONNUMERIC,                         delimiter = ' ')          # storing all the rows in an output list     output = []     for row in reader:         output.append(row[:])  for rows in output:     print(rows) 

Output:

output of gfg.py

And this is how it looks in the CSV file 'my_csv.csv' which gets created once we run the above code:

my_csv.csv

Reading numbers in a CSV file with quotes:

If quoting is set to csv.QUOTE_ALL then .writerow() will quote all fields and the numbers will now be stored in quotes. To read the numbers from each row, we make use of the reader object from CSV library and store all the rows within a list 'output', which we would also print afterward.

Code:

Python3
import csv  # creating a nested list of roll numbers, # subjects and marks scored by each roll number marks = [     ["RollNo", "Maths", "Python"],     [1000, 80, 85],     [2000, 85, 89],     [3000, 82, 90],     [4000, 83, 98],     [5000, 82, 90] ]  # using the open method with 'w' mode # for creating a new csv file 'my_csv' with .csv extension with open('my_csv.csv', 'w', newline = '') as file:     writer = csv.writer(file, quoting = csv.QUOTE_ALL,                         delimiter = ' ')     writer.writerows(marks)  # opening the 'my_csv' file to read its contents with open('my_csv.csv', newline = '') as file:     reader = csv.reader(file,                          quoting = csv.QUOTE_ALL,                         delimiter = ' ')          # storing all the rows in an output list     output = []     for row in reader:         output.append(row[:])  for rows in output:     print(rows) 

 Output:

output of gfg.py

And this how the above input gets stored within 'my_csv.csv' file:

my_csv.csv

Next Article
How to Read Text File Into List in Python?
author
mprerna802
Improve
Article Tags :
  • Technical Scripter
  • Python
  • Technical Scripter 2020
  • python-csv
Practice Tags :
  • python

Similar Reads

  • How to count the number of lines in a CSV file in Python?
    CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. A CSV file stores tabular data (numbers and text) in plain text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the
    2 min read
  • How To Read .Data Files In Python?
    Unlocking the secrets of reading .data files in Python involves navigating through diverse structures. In this article, we will unravel the mysteries of reading .data files in Python through four distinct approaches. Understanding the structure of .data files is essential, as their format may vary w
    4 min read
  • How to Read Text File Into List in Python?
    In this article, we are going to see how to read text files into lists in Python. File for demonstration: Example 1: Converting a text file into a list by splitting the text on the occurrence of '.'. We open the file in reading mode, then read all the text using the read() and store it into a variab
    2 min read
  • How to Read CSV Files with NumPy?
    Reading CSV files is a common task when working with data in Python. In this article we will see how to read CSV files using Numpy's loadtxt() and genfromtxt() methods. 1. Using NumPy loadtxt() methodThe loadtext() method is faster and simpler for reading CSV files. It is best when the file has cons
    2 min read
  • How to Read from a File in Python
    Reading from a file in Python means accessing and retrieving the contents of a file, whether it be text, binary data or a specific data format like CSV or JSON. Python provides built-in functions and methods for reading a file in python efficiently. Example File: geeks.txt Hello World Hello Geeksfor
    5 min read
  • How to read large text files in Python?
    In this article, we will try to understand how to read a large text file using the fastest way, with less memory usage using Python.  To read large text files in Python, we can use the file object as an iterator to iterate over the file and perform the required task. Since the iterator just iterates
    3 min read
  • How to read specific lines from a File in Python?
    Text files are composed of plain text content. Text files are also known as flat files or plain files. Python provides easy support to read and access the content within the file. Text files are first opened and then the content is accessed from it in the order of lines. By default, the line numbers
    3 min read
  • Reading CSV files in Python
    A CSV (Comma Separated Values) file is a form of plain text document that uses a particular format to organize tabular information. CSV file format is a bounded text document that uses a comma to distinguish the values. Every row in the document is a data log. Each log is composed of one or more fie
    5 min read
  • Read a file without newlines in Python
    When working with files in Python, it's common to encounter scenarios where you need to read the file content without including newline characters. Newlines can sometimes interfere with the processing or formatting of the data. In this article, we'll explore different approaches to reading a file wi
    2 min read
  • How to read a numerical data or file in Python with numpy?
    Prerequisites: Numpy  NumPy is a general-purpose array-processing package. It provides a high-performance multidimensional array object and tools for working with these arrays. This article depicts how numeric data can be read from a file using Numpy. Numerical data can be present in different forma
    4 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