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.

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:
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 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
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.
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.
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.
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'
That’s all!








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