How to write to CSV?

0164

To write to a CSV file in Python, you can use the csv module. Here's a simple example:

Example Code:

import csv

def write_to_csv(filename, data):
    with open(filename, mode='w', newline='') as file:
        writer = csv.writer(file)
        writer.writerow(['Name', 'Price'])  # Write header
        for item in data:
            writer.writerow(item)  # Write each row of data

# Example data
data = [
    ['Apple', 0.60],
    ['Banana', 0.50],
    ['Cherry', 0.75]
]

write_to_csv('fruits.csv', data)

Explanation:

  1. Import CSV Module: import csv imports the CSV module.
  2. Open File: with open(filename, mode='w', newline='') as file: opens the file in write mode. The newline='' argument prevents extra blank lines in Windows.
  3. Create CSV Writer: writer = csv.writer(file) creates a CSV writer object.
  4. Write Header: writer.writerow(['Name', 'Price']) writes the header row.
  5. Write Data: The loop for item in data: writes each row of data to the CSV file.

Usage:

Call the write_to_csv function with the desired filename and data to create a CSV file.

If you have any further questions or need clarification, feel free to ask!

0 Comments

no data
Be the first to share your comment!