Skip to main content

How to write data to a CSV file in Python

How to write data to a CSV file in Python.

Here's a step-by-step tutorial on how to write data to a CSV file in Python.

Step 1: Import the necessary modules First, you need to import the csv module, which provides functionality for working with CSV files. You also need to import any other modules you might need to create or manipulate the data you want to write to the CSV file.

import csv

Step 2: Prepare the data Next, you need to prepare the data that you want to write to the CSV file. This can be in the form of lists, dictionaries, or any other data structure that can be easily converted to CSV format. For demonstration purposes, let's say you have a list of dictionaries representing employees:

employees = [
{"Name": "John Doe", "Age": 30, "Position": "Manager"},
{"Name": "Jane Smith", "Age": 25, "Position": "Assistant"},
{"Name": "Mike Johnson", "Age": 35, "Position": "Supervisor"}
]

Step 3: Open the CSV file in write mode Now, you need to open the CSV file in write mode using the open() function. Specify the file path and name, and use the newline='' parameter to prevent blank lines from being inserted between rows.

with open('employees.csv', mode='w', newline='') as file:

Step 4: Create a CSV writer object Inside the with block, create a CSV writer object using the csv.writer() function. Pass in the file object and any other optional parameters you want to specify, such as the delimiter character (default is comma).

    writer = csv.writer(file)

Step 5: Write the header row (optional) If you want to include a header row in your CSV file, you can use the writerow() method of the CSV writer object to write a list of column names.

    writer.writerow(["Name", "Age", "Position"])

Step 6: Write the data rows Now, you can use a loop to iterate over the data and write each row to the CSV file using the writerow() method.

    for employee in employees:
writer.writerow([employee["Name"], employee["Age"], employee["Position"]])

Step 7: Close the file Finally, you need to close the file to free up system resources using the close() method.

    file.close()

That's it! You have successfully written data to a CSV file in Python. You can now open the file and see the data stored in CSV format.

Here's the complete code:

import csv

employees = [
{"Name": "John Doe", "Age": 30, "Position": "Manager"},
{"Name": "Jane Smith", "Age": 25, "Position": "Assistant"},
{"Name": "Mike Johnson", "Age": 35, "Position": "Supervisor"}
]

with open('employees.csv', mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age", "Position"])
for employee in employees:
writer.writerow([employee["Name"], employee["Age"], employee["Position"]])
file.close()

I hope this tutorial helps you understand how to write data to a CSV file in Python!