To write data to a CSV file in Python, you can use the csv
module. Here is an example of how to write data to a CSV file:
import csv
# Data to be written to the CSV file
data = [
['Name', 'Age', 'Country'],
['John', '25', 'USA'],
['Lisa', '30', 'Canada'],
['Tom', '35', 'UK']
]
# Specify the file name and mode ('w' for writing)
filename = 'data.csv'
# Open the file in write mode and create a CSV writer object
with open(filename, 'w', newline='') as file:
writer = csv.writer(file)
# Write the data to the CSV file
writer.writerows(data)
print(f'Data has been written to {filename}.')
In this example, we first import the csv
module. Then, we define the data to be written to the CSV file as a list of lists. Each inner list represents a row in the CSV file.
Next, we specify the file name and mode. In this case, we want to write to a new file, so we use 'w' as the mode.
We open the file using the open()
function and pass it the filename and mode. The newline=''
argument is used to prevent blank lines from being inserted between rows.
Inside the with
statement, we create a CSV writer object using the csv.writer()
function and pass it the file object. This writer object provides a method, writerows()
, to write the data to the CSV file.
Finally, we print a message indicating that the data has been written to the file.