Skip to content
  • (+91) 9409548155
  • support@appdividend.com
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
Menu
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
Python

How to Convert List to CSV in Python

  • 22 Jul, 2025
  • Com 2
Saving a List to CSV File in Python

Python’s csv Module provides the csv.writer() object to write a list into a CSV file. This object provides a writerow() method that writes a single row, whereas its writerows() method writes multiple rows.

Converting list to csv file in PythonThe primary purpose of this conversion is to save list-based data (e.g., lists of lists, dictionaries, or simple lists) into a text file, where each row represents an entry and columns are separated by commas (or other delimiters).

Single Flat List to CSV

If the input is a flat list, and you want to convert it into a CSV, the resulting file will be a single-column CSV. It is helpful for simple data, such as item names or IDs.

import csv


# Convert a flat list into a single-column CSV.
simple_list = ['apple', 'banana', 'orange']
with open('simple_list.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    for item in simple_list:
        writer.writerow([item])

Here is the output simple_list.csv file:

Single Flat List to CSV

The output is a single-column CSV file, where the first value in each column is the header and the subsequent values follow.

Each list item is written as a row with one column. `newline=”` prevents extra blank lines in Windows.

List of Lists to CSV

Each inner list represents a row with multiple columns, ideal for tabular data.

The writerows() method is efficient for writing multiple rows.

import csv

# Column names
column_names = ["Character Name", "Series Name", "Age"]

# Data rows
rows = [["Mando", "Mandalorian", 35],
        ["Grogu", "Mandalorian", 50],
        ["Eleven", "Stranger Things", 14],
        ["Jon", "Game of Thrones", 30],
        ["Ross", "Friends", 35]]

# Crafting a CSV file for writing
with open('showdata.csv', 'w') as f:
    write = csv.writer(f)
    write.writerow(column_names)
    write.writerows(rows)

print("List has been written to 'showdata.csv'")

# Output: List has been written to 'showdata.csv'

Here is the saved showdata.csv file:

List of Lists

List of Dictionaries to CSV

If the input list contains different dictionaries, you can use the dictionary keys as headers, which is perfect for structured data, such as JSON-like objects.

Use the csv’s DictWriter() method to simplify header and row writing.

import csv


def dict_to_csv():

    data = [
        {'name': 'Krunal', 'age': 32, 'city': 'New York'},
        {'name': 'Ankit', 'age': 30, 'city': 'London'},
        {'name': 'Rushabh', 'age': 33, 'city': 'Tokyo'}
    ]

    with open('dict_people.csv', 'w', newline='', encoding='utf-8') as file:
        fieldnames = ['name', 'age', 'city']
        writer = csv.DictWriter(file, fieldnames=fieldnames)

        writer.writeheader()  # Write column headers
        writer.writerows(data)

    print("Dictionary data written to dict_people.csv")


dict_to_csv()

# Output: Dictionary data written to dict_people.csv

List of Dictionaries

Empty List

If the list is empty, the output CSV file will also be empty. It will be created, but there won’t be any content.

import csv

data = []

with open("empty.csv", "w", newline='') as f:
    writer = csv.writer(f)
    writer.writerows(data)  # Writes nothing

print("Empty CSV file created successfully.")

# Output: Empty CSV file created successfully.

Empty CSV file

Missing values

If the list contains missing or empty values, such as None, the output CSV file will have empty fields.

import csv

list_with_missing = [['Kaynes Tech', 5782],
                     ['RR', None],
                     [None, 1431]]

with open('missing_values.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(['Name', 'Age'])
    writer.writerows(list_with_missing)

print("CSV file with missing values created successfully.")

# Output: CSV file with missing values created successfully.

Missing value while converting list to csv

Unicode and Non-ASCII Characters

The csv.writer.writerow() method supports non-ASCII characters (e.g., UTF-8 encoding).

import csv

unicode_list = [['José', 25],
                ['Müller', 30]]

with open('unicode_list.csv', 'w', newline='', encoding='utf-8') as f:
    writer = csv.writer(f)
    writer.writerow(['Name', 'Age'])
    writer.writerows(unicode_list)

print("CSV file with Unicode characters created successfully.")

# Output: CSV file with Unicode characters created successfully.

Unicode characters while converting a list to csv

Pandas to_csv() method

If the input is a list and a dictionary, first, convert the list to a DataFrame and then use the to_csv() function to convert the DataFrame into a CSV file.

import pandas as pd

char_name = ["Mando", "Grogu", "Eleven", "Jon", "Ross"]
series_name = ["Mandalorian", "Mandalorian",
               "Stranger Things", "Game of Thrones", "Friends"]
age = [35, 50, 14, 30, 35]

dict = {"Character Name": char_name,
        "Series Name": series_name,
        "Age": age}

# Convert the dictionary to a Pandas DataFrame
df = pd.DataFrame(dict)

# Save the DataFrame to a CSV file
df.to_csv('dataframe.csv', index=False)

print("List has been written to '.csv'")

# Output: List has been written to '.csv'

Pandas to_csv() method

That’s all!

Post Views: 259
Share on:
Krunal Lathiya

With a career spanning over eight years in the field of Computer Science, Krunal’s expertise is rooted in a solid foundation of hands-on experience, complemented by a continuous pursuit of knowledge.

How to Find the First Non-NaN Value in a Python List
Python XOR: How to Use Bitwise XOR Operator

2 Comments

  1. Rogerio Oliveira

    January 27, 2021 at 7:49 pm

    Caso eu atualizar a linha com novos dados, como faço para escrever na linha de baixo e não sobrescrever?

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Address: TwinStar, South Block – 1202, 150 Ft Ring Road, Nr. Nana Mauva Circle, Rajkot(360005), Gujarat, India

Call: (+91) 9409548155

Email: support@appdividend.com

Online Platform

  • Pricing
  • Instructors
  • FAQ
  • Refund Policy
  • Support

Links

  • About Us
  • Contact Us
  • Privacy Policy
  • Terms of services

Tutorials

  • Angular
  • React
  • Python
  • Laravel
  • Javascript
Copyright @2024 AppDividend. All Rights Reserved
Appdividend