Last modified: Nov 10, 2024 By Alexander Williams

Python CSV Writer: Write Data to CSV Files Like a Pro

Python's csv.writer() is a powerful tool for creating and writing data to CSV files. Similar to how you can read CSV files in Python, writing them is just as essential for data management.

Understanding CSV Writer Basics

The CSV writer object provides a systematic way to write data to CSV files. First, you'll need to import the csv module and create a file object in write mode.


import csv

with open('example.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(['Name', 'Age', 'City'])
    writer.writerow(['John', '25', 'New York'])

Writing Single Rows

Use writerow() method to write a single row of data. Each row should be provided as a list or tuple containing the values for each column.


import csv

with open('students.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(['ID', 'Name', 'Grade'])
    writer.writerow(['1', 'Alice', '95'])
    writer.writerow(['2', 'Bob', '87'])

Writing Multiple Rows at Once

For multiple rows, use writerows() method. This is more efficient than writing rows one by one, especially for large datasets.


import csv

data = [
    ['Name', 'Department', 'Salary'],
    ['Sarah', 'IT', '60000'],
    ['Mike', 'HR', '55000'],
    ['Lisa', 'Sales', '65000']
]

with open('employees.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerows(data)

Customizing the Delimiter

You can customize the delimiter when creating your writer object. This is useful when you need to convert data from other formats with different separators.


import csv

with open('data.csv', 'w', newline='') as file:
    writer = csv.writer(file, delimiter=';')
    writer.writerow(['Product', 'Price', 'Quantity'])
    writer.writerow(['Laptop', '999.99', '50'])

Error Handling and Best Practices

Always use the newline='' parameter when opening files to ensure consistent behavior across different platforms.


import csv

try:
    with open('output.csv', 'w', newline='') as file:
        writer = csv.writer(file)
        writer.writerow(['Header1', 'Header2'])
except IOError as e:
    print(f"An error occurred: {e}")

Working with Different Dialects

CSV writer supports different dialects for various CSV formats. The default is 'excel', but you can specify others or create custom dialects.


import csv

with open('custom.csv', 'w', newline='') as file:
    writer = csv.writer(file, dialect='excel-tab')
    writer.writerow(['Column1', 'Column2'])

Conclusion

The CSV writer in Python provides a flexible and efficient way to create and write to CSV files. Understanding its features and best practices helps in managing data effectively.

Remember to always close your files properly by using the context manager (with statement) and handle potential errors appropriately.