This tutorial provides a comprehensive guide on how to write a list to a CSV file in Python. The list may contain various data types such as strings, integers, and floating-point values. CSV stands for Comma-Separated Values, which is a widely used format for representing tabular data. It is easily interpretable by various applications and provides a simple way to organize and exchange data in a structured manner. It uses commas to separate data fields in a row, and each new line represents a new row.
The simplicity and compatibility of CSV make it a preferred choice for data storage. In addition to lists, other data structures can also be easily converted into CSV format. This flexibility allows various data types, such as dictionaries or tuples, to be efficiently represented and manipulated in CSV files. Python offers standard methods to open and manipulate CSV files, which will be thoroughly explored in this tutorial.
If you want to learn more about Python Programming, Visit Python Programming Tutorials.
Practical Use Of CSV files in Python
Using CSV (Comma-Separated Values) files offers several advantages.
- Their simple and human-readable structure makes them easy to create, read, and modify using various tools and programming languages, thanks to the comma-separated format.
- CSV files enjoy widespread support across platforms and applications, ensuring compatibility and seamless data exchange.
- CSV files are lightweight and efficient, with minimal overhead, making them ideal for storing and transferring large datasets.
Using Csv module to write a list to csv file
There are numerous ways to write data to CSV using the CSV Module. However, this tutorial will cover all the possible ways to write a list to CSV using the CSV module. Working with data from lists to CSV is convenient, as the CSV module automatically handles formatting and delimiters.
Writing a List to a CSV File Row-wise
To write a list to a CSV file in Python, we can use the csv.writer
module along with the writerow
function. CSV (Comma-Separated Values) files are a popular way to store tabular data, and using the csv.writer
and writerow
functions makes the process easier
Firstly, we need to open the CSV file in “write” mode using the open()
function and specifying the file mode as “w”. This will create a new file or overwrite the existing one. Here’s an example of how to do it:
import csv
# Sample list data
data = ['Laura Patrick', 30, 'laurapatrick@yahoo.com']
# Specify the file path where you want to save the CSV file
file_path = 'output.csv'
# Open the CSV file in 'w' mode (write mode) and specify newline='' to avoid blank lines
with open(file_path, 'w', newline='') as csvfile:
# Create a CSV writer object
csv_writer = csv.writer(csvfile)
# Write the list to the CSV file as a single row
csv_writer.writerow(data)
print(f"Data has been written to {file_path}.")
After running this code, you will find a CSV file named data.csv
in the same directory as your Python script, containing the data from the data
list. The image below shows how the content gets stored in the csv file.
Output:
In the provided code, the list ‘data’ is successfully written to a CSV file named ‘output.csv’ using the ‘csv.writer’ function in combination with the ‘writerow’ method. To achieve this:
- Open the file in “w” mode using the ‘open()’ function to access the file.
- Store the CSV file as an object in the ‘csvfile’ variable.
- Create a ‘writer’ object using the ‘csv.writer’ function, passing the ‘csvfile’ as an argument.
- Use the ‘writerow’ method of the ‘writer’ object to write the entire list as a row in the CSV file.
Writing a list of lists in a CSV file
When working with data in real-world scenarios, it is quite common to deal with large datasets. These datasets can contain vast amounts of information, making it essential to have efficient methods for storing and managing them. For such cases where the dataset consists of a list of lists, the writerows()
function from the CSV module is more suitable for storing and writing data to a CSV file in Python. This function allows us to efficiently write multiple rows of data to the CSV file.
- First, import the ‘csv’ module from the Python built-in packages.
- Store the list of lists in a variable
- Use the open() function with the ‘with’ context manager to write the list to a CSV file named ‘output.csv’. Specify the writing mode with the ‘w’ specifier. The ‘with’ statement automatically closes the file after execution within its body.
- When writing CSV files, include the newline=” parameter to ensure that each list in the ‘data’ variable corresponds to a row in the CSV file.
- Utilize the csv.writer() function to write the data to the CSV file.
- To write all the rows from the ‘data’ list to the CSV file, use the writer.writerows(data) function. Each inner list in the ‘data’ list represents a row in the CSV file.
Here’s an example code of writing a list of lists to a CSV file:
import csv
# Sample list data to be written to the CSV file
plant_growth_factors = [
["Plant Name", "Water Level", "Sunlight Level", "Temperature"],
["Rose", "High", "Medium", "20°C"],
["Lily", "Medium", "High", "25°C"],
["Tulip", "Low", "High", "22°C"],
["Cactus", "Low", "High", "30°C"],
]
# Open the CSV file in "write" mode
with open('output.csv', 'w', newline='') as csvfile:
# Create a CSV writer object
csvwriter = csv.writer(csvfile)
# Write each row of the list to the CSV file
for row in plant_growth_factors:
csvwriter.writerow(row)
print("Data written to CSV file successfully!")
Output:
Data written to CSV file successfully!
Once all the rows are written, the code prints “Data written to CSV file successfully!” to indicate that the operation was completed successfully. If executed, this code will create a CSV file named ‘output.csv’ in the same directory as the Python script, containing the data from the ‘plant_growth_factors’ list. The snapshot of the file is given below:
Each row of the list will correspond to a row in the CSV file, with values separated by commas.
write a list of dictionaries to a CSV file
Another straightforward approach to writing a list to a CSV file is using the Python module. However, the CSV class Dictwriters() write the List to a CSV file In Python. Let’s explore how it executes;
- Considering filenames for the CSV file.
- Define a list containing a list of Dictionaries, a ‘rulerships’, and ‘zodiac_signs’ as a key.
- Then open the CSV file using a Dictwriter() class in a writing mode ‘w’ by context manager ‘with.’
- The writeheaders() write the filenames/rows in the CSV file.
- The writerows() function uses to write a List of data to a CSV in multiple rows in a file.
- Each row prints dictionaries in a list as a string and corresponding filenames in the output CSV file.
import csv
rulerships = [ 'rulerships', 'zodiac_signs' ]
zodiac_signs = [{ 'rulerships': 'Fire', 'zodiac_signs': ['Leo', 'Aries', 'Sagittarius'] },
{ 'rulerships': 'Water', 'zodiac_signs': ['Pisces', 'Scorpio', 'Cancer'] },
{ 'rulerships': 'Earth', 'zodiac_signs': ['Taurus', 'Virgo', 'Capricorn'] },
{ 'rulerships': 'Air', 'zodiac_signs': ['Aquarius', 'Gemini', 'Libra'] }]
with open('output.csv', 'w', newline='') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=rulerships)
writer.writeheader() #write headers
writer.writerows(zodiac_signs) #write list of dictionaries
rulerships,zodiac_signs
Fire,"['Leo', 'Aries', 'Sagittarius']"
Water,"['Pisces', 'Scorpio', 'Cancer']"
Earth,"['Taurus', 'Virgo', 'Capricorn']"
Air,"['Aquarius', 'Gemini', 'Libra']"
Using the open() function, and list comprehension
Using the `open()` function with `csv.writer` and list comprehension allows you to effectively write a list of lists to CSV data in Python.
Here’s how, with all these functions, you will efficiently create CSV files containing well-structured representations of list data.
- Consider a list, and store its data into a variable, ‘horoscope.’
- Now, using the open() function with the help of a statement, ‘with’, you can write a list in a CSV object file ‘output.csv’, ensuring the writing mode with ‘w’, specifier. However, The ‘with’ statement automatically closes the code if executed within its body.
- The csv.writer() function writes the list data to the CSV file.
import csv
#consider a list
horoscope = ['Capricorn', 'Aquarius', 'Pieces', 'Aries', 'Taurus']
#using open function by the context manager 'with'
with open('output.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerows([[item] for item in horoscope])
Using for…in structure instead of list comprehension
import csv
horoscope = ['Capricorn', 'Aquarius', 'Pieces', 'Aries', 'Taurus']
with open('output.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
# writer.writerows([[item] for item in horoscope])
for item in horoscope:
writer.writerow([item])
Capricorn
Aquarius
Pieces
Aries
Taurus
In the following method, we use list comprehension to write data row-wise in a separate element in the CSV file.
Writing data in categories or defining headers as sub-lists using a list comprehension approach is also possible. You can write a list in a CSV file using list comprehension.
import csv
rulerships = [ 'Fire', 'Water', 'Earth', 'Air' ]
zodiac_signs = [[ 'Leo', 'Pisces', 'Taurus', 'Aquarius' ],
[ 'Aries', 'Scorpio', 'Virgo', 'Gemini' ],
[ 'Sagittarius','Cancer', 'Capricorn', 'Libra' ]]
with open('output.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(rulerships)
#writer.writerows([ [item for item in items] for items in zodiac_signs])
writer.writerows([[item for item in sublist] for sublist in zodiac_signs])
Output
Fire,Water,Earth,Air
Leo,Pisces,Taurus,Aquarius
Aries,Scorpio,Virgo,Gemini
Sagittarius,Cancer,Capricorn,Libra
To write a list to cSV Using the numpy module in Python
We can even use the numpy module in Python to read and write data into a CSV file. The numpy library imports as ‘num’ for shorthand functionalities. The numpy library supports reshaping a list and saving the reshaped data into a CSV file.
import numpy as num
#importing numpy library as a shorthand 'num',
capricorn_zodiac_sign = ['Martin Luther King Jr.','Michelle Obama', 'LeBron James']
reshaped_data = num.reshape(capricorn_zodiac_sign, (len(capricorn_zodiac_sign), 1))
num.savetxt('output.csv', reshaped_data, delimiter='-', fmt='%s')
- Consider importing the library as shorthand ‘num.’
- Consider a list ‘capricorn_zodiac_sign’ containing data as a string.
- Using the numpy reshape() function to reshape the list data. However, the reshape function composes two arguments. However, the first argument is the list on which reshape function applies, and the second function reflects the reshaped list structure. The reshaped list is a 2-D array with 3 rows and one column.
- The numpy function of the savetxt() is used to write list to a CSV file. It takes four arguments,
- The first argument is the file in which the list data is been written and translated to a CSV file.
- The second argument reflects the reshaped list.
- The third argument represents the specifier used to separate the values in the file.
- And the fourth argument depicts the formatting specifier. Here in this code, the specifier is ‘%s’, depicting that the data is been written in the file as a string.
The output of the above program is:
Martin Luther King Jr.
Michelle Obama
LeBron James
To write a list To CSV Using the Pandas Module
Pandas is a powerful open-source data manipulation and analysis library for Python. In addition to providing high-performance and easy-to-use data structures, it also provides data analysis tools. However, Pandas are also expected to read and visualise data from CSV files. Panda support to write a list of data in a CSV file.
import pandas as pd
data = ['Capricorn', 'Aquarius', 'Pieces', 'Aries', 'Taurus']
df = pd.DataFrame({'horoscope': data})
df.to_csv('output.csv', index=False)
Here’s how it executes a list of data in a CSV file using a straightforward pointer:
- Importing Pandas library and considering a List.
- Pandas Dataframe() function will create the dictionary containing information about the List.
- The pandas to_csv() function writes a list to a CSV effectively. However, the to_csv() argument ‘index’ sets to True to write the row indices (0,1,2…) to the CSV file.
- Using the to_csv() Pandas function makes an easier approach to access and write the list to CSV file in Python.
horoscope
Capricorn
Aquarius
Pieces
Aries
Taurus
Conclusion
CSV Module, Numpy, and Pandas are the most common modules to read and write CSV files, as they efficiently perform different types of operations, such as data analysis. It depends on the problem to help you decide which module to use. However, Write a list to a CSV file that contains structured data, which helps store, exchange, and analyse tabular data.