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:
- Import CSV Module:
import csvimports the CSV module. - Open File:
with open(filename, mode='w', newline='') as file:opens the file in write mode. Thenewline=''argument prevents extra blank lines in Windows. - Create CSV Writer:
writer = csv.writer(file)creates a CSV writer object. - Write Header:
writer.writerow(['Name', 'Price'])writes the header row. - 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!
