How To Read CSV to List in Python
In this tutorial, we will learn how to read CSV to list in python. First, let's discuss the CSV.
What is CSV File?
- CSV (Comma Separated Values) is a plain text file. These CSV files are used in different applications for exchanging data like contact managers and databases.
- These CSV files are also called Comma Delimited Files or Character Separated Values.
- The different names are given to CSV files since we can export complex data from one application to a CSV file and then we can import data from these CSV file data into another application.
Reading CSV files into List in Python.
- We 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 contents to list with or without headers.
Example: Reading CSV to List in Python
This is a sample CSV file that will be used to read into a list.
Id, Name, Course, City, Session
1, Bheem, Python, India, Morning
2, Chutki, Python, London, Evening
3, Tom, Python, USA, Morning
4, Jerry, Python, Japan, Morning
- Now we have to read this file into a list of lists in python.
- Initially, Import CSV to a list of lists using CSV. reader.
- Python has a built-in CSV module, it will help to read the data from the CSV file using a reader class. i.e, from CSV import reader.
import csv
with open('students.csv', 'r') as read_obj: # read csv file as a list of lists
csv_reader = csv.reader(read_obj) # pass the file object to reader() to get the reader object
list_of_rows = list(csv_reader) # Pass reader object to list() to get a list of lists
print(list_of_rows)
[['Id', 'Name', 'Course', 'Country', 'Session'],
['1', 'Bheem', 'Python', 'India', 'Morning'],
['2', 'Chutki', 'Python', 'London', 'Evening'],
['3', 'Tom', 'Python', 'USA', 'Morning'],
['4', 'Jerry', 'Python', 'Japan', 'Morning']]
- It created a list of lists containing all rows of the CSV file and print that list of lists.
- Here, in the first step, the file is read to be open, so open the file in reading mode and later transfer that file object into the function csv_reader().
- It will result in an iterator, which can be used to iterate over all the lines of the CSV file.
- We want the result in list format so the list() function is used to return the result in the list of the list.
- The obtained result row of CSV and each item in the list represents a cell/column in that row.
Example 2: Selection of data by using row and column numbers
By using a list of lists created above we can select individual data by using row and column numbers.
row_number = 2
col_number = 1
value = list_of_rows[row_number - 1][col_number - 1]
print('Value in a cell at 2nd row and 1st column : ', value
Value in a cell at 2nd row and 1st column: 1
Example 3: Using Pandas to read CSV
The below example shows how to read the CSV file into a list without the header by using the pandas library.
import pandas as pd
df = pd.read_csv('students.csv', delimiter=',')
list_of_rows = [list(row) for row in df.values]
print(list_of_rows)
['1', 'Bheem', 'Python', 'India', 'Morning'],
['2', 'Chutki', 'Python', 'London', 'Evening'],
['3', 'Tom', 'Python', 'USA', 'Morning'],
['4', 'Jerry', 'Python', 'Japan', 'Morning']]
- Here, first, upload the CSV file into a data frame using read_csv().
- Dataframe values return all rows in 2d Numpy format excluding the header.
- Then we iterated over all rows of this obtained result using list comprehension and created a list of lists.
Example 4: Read CSV files into a list of tuples using Python
- First upload data from the above CSV file that is Student.csv into a list of tuples, where each tuple in the list represents a row and each data in the tuple represents a cell.
with open('students.csv', 'r') as read_obj: # pass the file object to reader() to get the reader object
csv_reader = reader(read_obj) # Get all rows of csv from csv_reader object as list of tuples
list_of_tuples = list(map(tuple, csv_reader)) # display all rows of csv
print(list_of_tuples)
[('Id', 'Name', 'Course', 'Country', 'Session'),
('1', 'Bheem', 'Python', 'India', 'Morning'),
('2', 'Chutki', 'Python', 'London', 'Evening'),
('3', 'Tom', 'Python', 'USA', 'Morning'),
(4', 'Jerry', 'Python', 'Japan', 'Morning')]
Example 5: Read CSV into a list of dictionaries using Python
By using the DictReader module, we can read CSV into a list of dictionaries.
from CSV import DictReader # open file in the read mode
with open('students.csv', 'r') as read_obj: # pass the file object to DictReader() to get the DictReader object
dict_reader = DictReader(read_obj) # get a list of dictionaries from dct_reader
list_of_dict = list(dict_reader) # print list of dict i.e. rows
print(list_of_dict)
[{‘Id’:'1', ‘Name’:'Bheem',’Course’:'Python',’Country’: 'India', ‘Session’:'Morning'},
{‘Id’:2', ‘Name’: 'Chutki', ’Course’: 'Python', ’Country’:'London', ‘Session’: 'Evening'},
{‘Id’:'3', ‘Name’:'Tom', ’Course’: 'Python', ’Country’: 'USA', ‘Session’: 'Morning'},
{‘Id’:'4', ‘Name’:'Jerry', ’Course’:'Python', ’Country’:'Japan', ‘Session’: 'Morning'}]
Conclusion
In this tutorial, we learned how to read a CSV file to List from different approaches.