Getting Started

Python - IntroductionPython - Hello World ProgramPython - SyntaxPython - Data TypesPython - Variables

Operators

Python - Arithmetic OperatorsPython - Relational OperatorsPython - Logical OperatorsPython - Assignment OperatorsPython - Bitwise OperatorsPython - Membership OperatorsPython - Identity OperatorsPython - Increment and Decrement Operators

Conditions

Python - If Else statement

Loop

Python - While LoopPython - For Loop

Numbers

Python - NumbersPython - Number Conversion

Strings

Python - StringsPython - String OperatorsPython - String FormattingPython - String MethodsPython - String Format Method

List

Python - ListPython - List Methods

Tuple

Python - Tuple

Set

Python - SetPython - Set Methods

Dictionary

Python - DictionaryPython - Dictionary Methods

Functions

Python - FunctionsPython - Functions - Variable length argumentsPython - Lambda Function

Scope of Variables

Python - Scope of Variables

Modules

Python - ModulesPython - Math ModulePython - JSON ModulePython - datetime ModulePython - time Module

I/O

Python - Read input from keyboard

File

Python - File Handling

Exception Handling

Python - Exception Handling

OOP

Python - Classes and ObjectsPython - Class Constructor __init__ methodPython - Class Destructor __del__ methodPython - Built-in Class AttributesPython - InheritancePython - Method OverridingPython - Method Overloading

Package Management

Python - PIP

Python - MySQL

Python - MySQL - Getting StartedPython - MySQL - Insert dataPython - MySQL - Select dataPython - MySQL - Update dataPython - MySQL - Delete data

Python - CSV

Python - Read data from CSV filePython - Write data in CSV file

Python - Write data in CSV file

Python

← Prev
python logo

In this tutorial we will learn to write data in CSV file in Python.

In the previous tutorial we covered how to read data from CSV file. Feel free to check that out.

Import the csv module

To save data in CSV file we have to take help of the csv module. So, go ahead and import the module by writing the following code.

import csv

Write data in CSV file

To write data in CSV file we will first create a new file using the open() method.

Let's name our file as sample.csv.

To write data we will use the DictWriter class of the csv module. We will pass the file object that holds the reference to the newly created CSV file and the variable that holds the fields name.

To write the fields name we will use the writeheader() method.

To write the data rows we will use the writerow() method.

Sample data

For this tutorial we will write the following data in the sample.csv file.

playerid,score
1,10
2,9
3,12

Where, playerid,score in the 1st row are the fields. The remaining 3 rows are the data.

Write data using dictionary

In the following Python program we are writing the sample data in sample.csv file.

The data is in dictionary form inside a list.

# import module
import csv

try:
    # create file
    fobj = open('score.csv', 'w')
    
    # fields
    fields = ['playerid', 'score']

    # data to save in csv file
    data = [
        {'playerid': 1, 'score': 10},
        {'playerid': 2, 'score': 9},
        {'playerid': 3, 'score': 12}
    ]
    
    # writer
    writer = csv.DictWriter(fobj, fields)
    
    # write the header
    writer.writeheader()
    
    # write the data
    for row in data:
        writer.writerow(row)
    
except:
    print("An error occurred while writing the file.")

finally:
    fobj.close()

On executing the above code we will get the sample.csv file containing the following data.

playerid,score
1,10
2,9
3,12
← Prev

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT