Python Tutorial

Python Flow Control

Python Functions

Python Data Types

Python Date and Time

Python Files

Python String

Python List

Python Dictionary

Python Variable

Python Input/Output

Python Exceptions

Python Advanced

Write CSV file in Python

To write a CSV (Comma Separated Values) file in Python, you can use the built-in csv module. This module provides two main classes for writing CSV files: csv.writer and csv.DictWriter. In this tutorial, we will discuss how to write a CSV file using both classes.

  • Using csv.writer:

The csv.writer class provides two methods for writing rows to a CSV file: writerow() and writerows(). Here's how to write a CSV file using csv.writer:

import csv

file_name = 'output.csv'

header = ['Name', 'Age', 'Occupation']
data = [
    ['Alice', 30, 'Engineer'],
    ['Bob', 25, 'Doctor'],
    ['Charlie', 22, 'Student']
]

with open(file_name, 'w', newline='') as csvfile:
    csv_writer = csv.writer(csvfile)
    
    # Write header (column names)
    csv_writer.writerow(header)
    
    # Write rows
    for row in data:
        csv_writer.writerow(row)

In this example, the with open(file_name, 'w', newline='') as csvfile: statement opens the CSV file in write mode. The csv.writer class is used to create a writer object, and the writerow() method is used to write the header (column names) and the rows.

  • Using csv.DictWriter:

The csv.DictWriter class provides two methods for writing rows to a CSV file using dictionaries: writeheader() and writerows(). Here's how to write a CSV file using csv.DictWriter:

import csv

file_name = 'output.csv'

header = ['Name', 'Age', 'Occupation']
data = [
    {'Name': 'Alice', 'Age': 30, 'Occupation': 'Engineer'},
    {'Name': 'Bob', 'Age': 25, 'Occupation': 'Doctor'},
    {'Name': 'Charlie', 'Age': 22, 'Occupation': 'Student'}
]

with open(file_name, 'w', newline='') as csvfile:
    csv_writer = csv.DictWriter(csvfile, fieldnames=header)
    
    # Write header (column names)
    csv_writer.writeheader()
    
    # Write rows
    for row in data:
        csv_writer.writerow(row)

In this example, the csv.DictWriter class is used to create a writer object with the specified fieldnames (column names). The writeheader() method is used to write the header, and the writerow() method is used to write the rows.

In conclusion, you can use the csv module in Python to write CSV files. The csv.writer class writes the file using lists for each row, while the csv.DictWriter class writes the file using dictionaries for each row with keys corresponding to the column names.

  1. Using the csv module in Python for file writing:

    • Description: The csv module in Python provides functionality for writing data to CSV files.
    • Code:
    import csv
    
    data = [['Name', 'Age'], ['Alice', 25], ['Bob', 30], ['Charlie', 35]]
    
    with open('example.csv', 'w', newline='') as file:
        writer = csv.writer(file)
        writer.writerows(data)
    
  2. Pandas library for writing data to CSV files in Python:

    • Description: Pandas provides a convenient to_csv method for writing data to CSV files.
    • Code:
    import pandas as pd
    
    data = {'Name': ['Alice', 'Bob', 'Charlie'],
            'Age': [25, 30, 35]}
    
    df = pd.DataFrame(data)
    df.to_csv('example.csv', index=False)
    
  3. CSV file writing and data manipulation in Python:

    • Description: Write data to a CSV file and perform data manipulation before writing.
    • Code:
    data = [['Name', 'Age'], ['Alice', 25], ['Bob', 30], ['Charlie', 35]]
    
    # Perform data manipulation
    
    with open('example.csv', 'w', newline='') as file:
        writer = csv.writer(file)
        writer.writerows(data)
    
  4. Handling different delimiters in CSV files with Python:

    • Description: The csv module supports different delimiters, such as tabs or semicolons.
    • Code:
    data = [['Name', 'Age'], ['Alice', 25], ['Bob', 30], ['Charlie', 35]]
    
    with open('example.tsv', 'w', newline='') as file:
        writer = csv.writer(file, delimiter='\t')
        writer.writerows(data)
    
  5. Writing specific columns to a CSV file in Python:

    • Description: Use Pandas to select and write specific columns to a CSV file.
    • Code:
    import pandas as pd
    
    data = {'Name': ['Alice', 'Bob', 'Charlie'],
            'Age': [25, 30, 35],
            'City': ['New York', 'London', 'Tokyo']}
    
    df = pd.DataFrame(data)
    selected_columns = ['Name', 'Age']
    df[selected_columns].to_csv('example.csv', index=False)
    
  6. Adding headers and customizing output in CSV file writing:

    • Description: Customize headers and other options when writing data to a CSV file.
    • Code:
    data = [['Alice', 25], ['Bob', 30], ['Charlie', 35]]
    
    with open('example.csv', 'w', newline='') as file:
        fieldnames = ['Name', 'Age']
        writer = csv.writer(file)
        writer.writerow(fieldnames)
        writer.writerows(data)
    
  7. Error handling and exception handling in CSV file writing in Python:

    • Description: Implement error handling to deal with potential issues during CSV file writing.
    • Code:
    import csv
    
    data = [['Name', 'Age'], ['Alice', 25], ['Bob', 30], ['Charlie', 35]]
    
    try:
        with open('example.csv', 'w', newline='') as file:
            writer = csv.writer(file)
            writer.writerows(data)
    except PermissionError:
        print("Permission error. Unable to write to file.")
    
  8. Appending to an existing CSV file in Python:

    • Description: Append new data to an existing CSV file.
    • Code:
    data = [['Diana', 28], ['Eva', 32]]
    
    with open('example.csv', 'a', newline='') as file:
        writer = csv.writer(file)
        writer.writerows(data)