Your Page Title
🔍

    Python Write CSV File

    Writing a CSV file in Python is one of the more common tasks aimed at data storage and transfer. Python provides the csv module that can take good care of opening, creating, and writing CSV files. Let me explain how you can write a CSV file stepwise.

    Steps to Write a CSV File

    1. Import the csv module

    The csv module provides functionality to both read from and write to CSV files.

    import csv

    2. Open a File in Write Mode

    Use Python’s built-in open() function to create or open a file in write mode ('w'). Use the newline='' argument to prevent adding extra blank lines on Windows.

    with open('output.csv', mode='w', newline='') as file:
    • output.csv: Name the new file or overwrite this output file.
    • mode='w': Opens the file in write mode.
    • newline='': Ensures proper line endings.

    3. Create a csv.writer object

    Use the csv.writer() function to generate a writer object that will take care of the rows writing.

    writer = csv.writer(file)

    4. Write rows to the CSV file

    Use the writer.writerow() method to write a single row and the writer.writerows() method to write multiple rows.

    • Single Row: Pass a list of values for one row.
    • Multiple Rows: Accept a list of lists where each inner list is a row.

    Example:

    # Writing a single row
    writer.writerow(['Name', 'Age', 'City'])
    
    # Writing multiple rows
    writer.writerows([
        ['Alice', 25, 'New York'],
        ['Bob', 30, 'San Francisco'],
        ['Charlie', 35, 'Los Angeles']
    ])

    Complete Example

    Here’s a complete example of writing a CSV file:

    import csv
    
    # File path to save the CSV
    file_path = 'example.csv'
    
    # Data to write
    header = ['Name', 'Age', 'City']
    rows = [
        ['Alice', 25, 'New York'],
        ['Bob', 30, 'San Francisco'],
        ['Charlie', 35, 'Los Angeles']
    ]
    
    # Writing to the CSV file
    with open(file_path, mode='w', newline='') as file:
       writer = csv.writer(file)
     
       # Write the header
       writer.writerow(header)
    
       # Write the data rows
       writer.writerows(rows)
    
    print(f"CSV file '{file_path}' written successfully.")

    Handling Advanced Scenarios

    1. Custom Delimiters

    You can customize the delimiter by passing the delimiter argument to csv.writer().

    writer = csv.writer(file, delimiter=';') # Use semicolon as delimiter

    2. Writing Dictionaries

    If your data is in the form of dictionaries, use csv.DictWriter.

    If your data is in the form of dictionaries, use csv.DictWriter.

    import csv

    # Data in dictionary format
    data = [
    {'Name': 'Alice', 'Age': 25, 'City': 'New York'},
    {'Name': 'Bob', 'Age': 30, 'City': 'San Francisco'},
    {'Name': 'Charlie', 'Age': 35, 'City': 'Los Angeles'}
    ]

    # Writing to CSV file
    with open('dict_example.csv', mode='w', newline='') as file:
    # Create a DictWriter object
    writer = csv.DictWriter(file, fieldnames=['Name', 'Age', 'City'])

    # Write the header
    writer.writeheader()

    # Write the rows
    writer.writerows(data)

    print("CSV file written successfully with dictionary data.")

    Key Points to Remember

    1. File Path: Ensure the file path is correct, especially if saving to a specific directory.
    2. Encoding: Use the encoding argument if dealing with non-ASCII characters (e.g., UTF-8).
    3. Exception Handling: Use try-except blocks to handle errors like file permissions or invalid data.