write to a csv file in python

Here's an example code snippet that demonstrates writing data to a CSV file in Python:

main.py
import csv

# Define data to be written to CSV file
data = [
  ['John', 'Doe', 35],
  ['Jane', 'Doe', 28],
  ['Bob', 'Smith', 42]
]

# Open CSV file for writing
with open('output.csv', mode='w', newline='') as csv_file:
  # Create CSV writer object
  writer = csv.writer(csv_file)

  # Write data to CSV file
  for row in data:
    writer.writerow(row)
353 chars
18 lines

In this example, we import the CSV module to handle CSV file operations. We define the data to be written to the CSV file as a list of lists, where each inner list represents a row in the CSV file.

Next, we use the open() function to open a CSV file for writing. We specify the file name, open mode ('w' for write mode), and newline='' to prevent empty rows from being written between each row of data.

We then create a CSV writer object using csv.writer(), passing in the opened CSV file. Finally, we use a loop to iterate over the data and write each row to the CSV file using the writer object's writerow() method.

gistlibby LogSnag