How to Create CSV File in Python?

Anuradha GuptaAnuradha Gupta
1 min read

To create a CSV file using Python, you can follow these steps:

  1. Import the csv module.

  2. Open a file in write mode using open() function.

  3. Create a csv.writer object.

  4. 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

Anuradha Gupta
Anuradha Gupta