The Wayback Machine - https://web.archive.org/web/20240621190958/https://www.geeksforgeeks.org/how-to-read-numbers-in-csv-files-in-python/
Open In App

How to read numbers in CSV files in Python?

Last Updated : 12 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
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



Similar Reads

Python program to read CSV without CSV module
CSV (Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet or database. 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 comma as a field separator is the source of the nam
3 min read
How to create multiple CSV files from existing CSV file using Pandas ?
In this article, we will learn how to create multiple CSV files from existing CSV file using Pandas. When we enter our code into production, we will need to deal with editing our data files. Due to the large size of the data file, we will encounter more problems, so we divided this file into some small files based on some criteria like splitting in
3 min read
Read multiple CSV files into separate DataFrames in Python
Sometimes you might need to read multiple CSV files into separate Pandas DataFrames. Importing CSV files into DataFrames helps you work on the data using Python functionalities for data analysis. In this article, we will see how to read multiple CSV files into separate DataFrames. For reading only one CSV file, we can use pd.read_csv() function of
2 min read
How to read all CSV files in a folder in Pandas?
In this article, we will see how to read all CSV files in a folder into single Pandas dataframe. The task can be performed by first finding all CSV files in a particular folder using glob() method and then reading the file by using pandas.read_csv() method and then displaying the content. Approach:Import necessary python packages like pandas, glob,
1 min read
How to Read CSV Files with NumPy?
In this article, we will discuss how to read CSV files with Numpy in Python. Reading CSV files using Python NumPy library helps in loading large amount of data quicker. Due to performance reason, NumPy is preferred while reading huge amount of data from CSV files. Dataset in use: Read CSV Files using built-in Python open() function Here we are not
3 min read
Pandas Read CSV in Python
CSV files are the Comma Separated Files. To access data from the CSV file, we require a function read_csv() from Pandas that retrieves data in the form of the data frame. Syntax of read_csv() Here is the Pandas read CSV syntax with its parameters. Syntax: pd.read_csv(filepath_or_buffer, sep=' ,' , header='infer', index_col=None, usecols=None, engin
4 min read
Python - Read CSV Column into List without header
Prerequisites: Reading and Writing data in CSV CSV files are parsed in python with the help of csv library. The csv library contains objects that are used to read, write and process data from and to CSV files. Sometimes, while working with large amounts of data, we want to omit a few rows or columns, so that minimum memory gets utilized. Let's see
2 min read
Python - Read CSV Columns Into List
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 comma as a field separator is the source of the name for this file format. In this article, we will read data from a CSV file into a list. We will use the panda's libr
3 min read
Read a CSV into list of lists in Python
In this article, we are going to see how to read CSV files into a list of lists in Python. Method 1: Using CSV moduleWe can read the CSV files into different data structures like a list, a list of tuples, or a list of dictionaries.We can use other modules like pandas which are mostly used in ML applications and cover scenarios for importing CSV con
2 min read
Read CSV File without Unnamed Index Column in Python
Whenever the user creates the data frame in Pandas, the Unnamed index column is by default added to the data frame. The article aims to demonstrate how to read CSV File without Unnamed Index Column using index_col=0 while reading CSV. Read CSV File without Unnamed Index Column Using index_col=0 while reading CSVThe way of explicitly specifying whic
2 min read
Practice Tags :
three90RightbarBannerImg