To write data to a CSV file in Python, you can use the built-in csv module. Below is an example code snippet that demonstrates how to write data to a CSV file:
import csv
# Define the data to be written to the CSV file
data = [
['Name', 'Age', 'City'],
['John', 25, 'New York'],
['Mary', 30, 'Chicago'],
['Bob', 40, 'San Francisco']
]
# Define the name of the CSV file to be created
filename = 'people.csv'
# Open the CSV file for writing
with open(filename, 'w', newline='') as csvfile:
# Create a CSV writer object
csvwriter = csv.writer(csvfile)
# Write the data to the CSV file
for row in data:
csvwriter.writerow(row)
In this example, we first 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.
We then define the name of the CSV file to be created.
Next, we open the CSV file for writing using the open () function, with the file mode set to 'w' to indicate that we want to write to the file. We also pass the newline='' parameter to avoid adding extra newline characters to the file.
Then, we create a CSV writer object using the csv.writer() function and pass in the opened CSV file object. This object will be used to write the data to the CSV file.
Finally, we loop through each row in the data and use the writerow () method of the CSV writer object to write the row to the CSV file.
Once the CSV file has been written, you can open it in a spreadsheet program like Excel or Google Sheets to view the data.