Open In App

Read a CSV into list of lists in Python

Last Updated : 08 Apr, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to see how to read CSV files into a list of lists in Python.

Method 1: Using CSV module

  • 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 1:

In this example, we are reading a CSV file and converting the string into the list.

 

Python3




import csv
  
with open('sample.csv', 'r') as read_obj:
  
    # Return a reader object which will
    # iterate over lines in the given csvfile
    csv_reader = csv.reader(read_obj)
  
    # convert string to list
    list_of_csv = list(csv_reader)
  
    print(list_of_csv)


Output:

[[‘JAN’, 34, 360, 417], [‘FEB’, 31, 342, 391], [‘MAR’, 36, 406, 419], [‘APR’, 34, 396, 461],

 [‘MAY’, 36, 420, 472], [‘JUN’, 43, 472, 535], [‘JUL’, 49, 548, 622], [‘AUG’, 50, 559, 606], 

 [‘SEP’, 40, 463, 508], [‘OCT’, 35, 407, 461], [‘NOV’, 31, 362, 390], [‘DEC’, 33, 405, 432]]

Example 2:

In this example, we are reading a CSV file and iterating over lines in the given CSV.

 

Python3




import csv
  
with open('example.csv') as csvfile:
    
    # Return a reader object which will
    # iterate over lines in the given csvfile.
    readCSV = csv.reader(csvfile, delimiter=',')
    for row in readCSV:
        print(row)
        print(row[0])
        print(row[0], row[1], row[2],)
        print("\n")


Output:

 

Method 2: Using Pandas

You can use the pandas library for this which has an inbuilt method to convert values to a list. Pandas.values property is used to get a numpy.array and then use the tolist() function to convert that array to list.

Note: For more information refer Read CSV Into List Using Pandas

Python3




# app.py
  
import pandas as pd
  
# Creating Dictionary
dict = {
    'series': ['Friends', 'Money Heist', 'Marvel'],
    'episodes': [200, 50, 45],
    'actors': [' David Crane', 'Alvaro', 'Stan Lee']
}
  
# Creating Dataframe
df = pd.DataFrame(dict)
print(df)


Output:

 



Previous Article
Next Article

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
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
Copying Csv Data Into Csv Files Using Python
CSV files, the stalwarts of information exchange, can be effortlessly harnessed to extract specific data or merge insights from multiple files. In this article, we unveil five robust approaches, transforming you into a virtuoso of CSV data migration in Python. Empower your data-wrangling endeavors, mastering the art of copying and organizing inform
4 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
PySpark - Read CSV file into DataFrame
In this article, we are going to see how to read CSV files into Dataframe. For this, we will use Pyspark and Python. Files Used: authorsbook_authorbooksRead CSV File into DataFrame Here we are going to read a single CSV into dataframe using spark.read.csv and then create dataframe with this data using .toPandas(). C/C++ Code from pyspark.sql import
2 min read
Python - Convert Lists into Similar key value lists
Given two lists, one of key and other values, convert it to dictionary with list values, if keys map to different values on basis of index, add in its value list. Input : test_list1 = [5, 6, 6, 6], test_list2 = [8, 3, 2, 9] Output : {5: [8], 6: [3, 2, 9]} Explanation : Elements with index 6 in corresponding list, are mapped to 6. Input : test_list1
12 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
How to read numbers in CSV files in Python?
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
4 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 :