You are on page 1of 8

CSV Files

What is a CSV ?

● CSV means Comma Separated Values).


● It is a simple file format used to store tabular data, such as a spreadsheet or
database.
● A CSV file stores tabular data (numbers and text) in plain text.
● Each line of the file is a data record.
● Each record consists of one or more fields, separated by commas.
● The use of the comma as a field separator is the source of the name for this
file format.
● For working CSV files in python, there is an inbuilt module called csv.
Reading a CSV file

import csv
with open('path/to/csv_file', 'r') as f:
csv_reader = csv.reader(f)
for line in csv_reader:
print(line)
output
['Name', 'Age', 'Profession']
['Jack', '23', 'Doctor']
['Miller', '22', 'Engineer']
Writing CSV files in Python

mport csv
i
SN,Movie,Protagonist
with open('innovators.csv', 'w', newline=' ') as file:

writer = csv.writer(file)
1,Lord of the Rings,Frodo Baggins
writer.writerow(["SN", "Name", "Contribution"]) 2,Harry Potter,Harry Potter
writer.writerow([1, "Linus Torvalds", "Linux Kernel"])

writer.writerow([2, "Tim Berners-Lee", "World Wide Web"])

writer.writerow([3, "Guido van Rossum", "Python Programming"])

You might also like