How to Create CSV File in Python?
Anuradha Gupta
1 min read
To create a CSV file using Python, you can follow these steps:
Import the
csv
module.Open a file in write mode using
open()
function.Create a
csv.writer
object.Write data to the CSV file using the
writerow()
method.
Here's a short example:
pythonCopy codeimport csv
# Data to be written to the CSV file
data = [
['Name', 'Age', 'City'],
['John', 25, 'New York'],
['Alice', 30, 'Los Angeles'],
['Bob', 22, 'Chicago']
]
# Open the file in write mode
with open('example.csv', mode='w', newline='') as file:
# Create a CSV writer object
writer = csv.writer(file)
# Write data to the CSV file row by row
for row in data:
writer.writerow(row)
print("CSV file created successfully.")
This code will create a CSV file named example.csv
with the provided data.
0
Subscribe to my newsletter
Read articles from Anuradha Gupta directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by