• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Lists / Convert List of Lists to CSV File in Python

Convert List of Lists to CSV File in Python

Author: Aditya Raj
Last Updated: May 5, 2022

Lists are one of the most frequently used data structures in python. In this article, we will discuss how we can convert a list of lists to a CSV file in python.

Table of Contents
  • List of Lists to CSV in Python Using csv.writer() 
  • Conclusion

List of Lists to CSV in Python Using csv.writer() 

The csv module provides us with different methods to perform various operations on a CSV file. To convert a list of lists to csv in python, we can use the csv.writer() method along with the csv.writerow() method. For this, we will use the following steps.

  • First, we will open a csv file in write mode using the open() function. The open() function takes the file name as the first input argument and the literal “w” as the second input argument to show that the file will be opened in the write mode. It returns a file object that contains the empty csv file created by the open() function.
  • After opening the file, we will create a csv.writer object using the csv.writer() method. The csv.writer() method takes the file object as an input argument and returns a writer object. Once the writer object is created, we can add data from the list of lists to the csv file using the csv.writerow() method.
  • The csv.writerow() method, when invoked on a writer object, takes a list of values and adds it to the csv file referred by the writer object.
  • First, we will add the header for the CSV file. For this, we will pass a list of column names to the writerow() method
  • After adding the header, we will use a for loop with the writerow() method to add each list to the csv file. Here, we will pass each list one by one to the writerow() method. The writerow() method adds the list to the csv file. 

After execution of the for loop, the data from the list will be added to the CSV file. To save the data, you should close the file using the close() method. Otherwise, no changes will be saved to the csv file.

The source code to convert a list of lists to a csv file using the csv.writer() method is as follows.

import csv

listOfLists = [["Aditya", 1, "Python"], ["Sam", 2, 'Java'], ['Chris', 3, 'C++'], ['Joel', 4, 'TypeScript']]
print("THe list of lists is:")
print(listOfLists)
myFile = open('demo_file.csv', 'w')
writer = csv.writer(myFile)
writer.writerow(['Name', 'Roll', 'Language'])
for data_list in listOfLists:
    writer.writerow(data_list)
myFile.close()
myFile = open('demo_file.csv', 'r')
print("The content of the csv file is:")
print(myFile.read())
myFile.close()

Output:

THe list of lists is:
[['Aditya', 1, 'Python'], ['Sam', 2, 'Java'], ['Chris', 3, 'C++'], ['Joel', 4, 'TypeScript']]
The content of the csv file is:
Name,Roll,Language
Aditya,1,Python
Sam,2,Java
Chris,3,C++
Joel,4,TypeScript

Conclusion

In this article, we have discussed an approach to convert a list of lists to csv file in python. In these approaches,  each list will be added to the csv file irrespective of whether it has the same number of elements as compared to the columns in the csv or not. Thus it is advised to make sure that each element should have the same number of element. Also, You should make sure that the order of element present in the lists should be same. Otherwise, the data appended to the csv file will become inconsistent and will lead to errors. 

To know more about lists in python, you can read this article on list comprehension in python. You might also like this article on dictionary comprehension in python.

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Lists Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Pyspark Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehension in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Count Rows With Null Values in PySpark
  • PySpark OrderBy One or Multiple Columns
  • Select Rows with Null values in PySpark
  • PySpark Count Distinct Values in One or Multiple Columns
  • PySpark Filter Rows in a DataFrame by Condition

Copyright © 2012–2025 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us