csv CSV file processing in various languages Reading and writing in Python


CSV(Comma Separated Values) is a simple file format used to store tabular data, such as a spreadsheet. This is a minimal example of how to write & read data in Python.

Writing data to a CSV file:

import csv
data = [["Ravi", "9", "550"], ["Joe", "8", "500"], ["Brian", "9", "520"]]
with open('students.csv', 'wb') as csvfile:
    writer = csv.writer(csvfile, delimiter=',')

Reading data from a CSV file:

import csv
with open('students.csv', 'rb') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=',',)
    for row in spamreader:
        print("Name: {} class: {} Marks: {}".format(row[0], row[1], row[2]))
Name: Ravi class: 9 Marks: 550
Name: Joe class: 8 Marks: 500
Name: Brian class: 9 Marks: 520