Theory on CSV Files
# Introduction
A CSV (Comma Separated Values) file is a simple type of text file used to store data in a table format. It's commonly used for exchanging data because it's easy to read and create. Each line in a CSV file represents a row in the table, and commas are used to separate the values in each column. CSV files have .csv as file extension.
Let us take a CSV file named data.csv which has the following contents:
Roll No., Name of student, stream, Marks
1, Panda, Science, 426
2, Piyush, Science, 445
As you can see each row is a new line, and each column is separated with a comma. This is an example of how a CSV file looks like.
To work with csv files, we have to import the csv module in our program.
# Read a CSV file:
To read data from a CSV file, we have to use reader( ) function.
The reader function takes each row of the file and make a list of all columns.
Code :
import csv
f=open("csvfile.csv", "r")
s = csv.reader(f)
for i in s:
print(i)
print("Data successfully read.")
Output :
['Aditya', 'Kumkar', 'Engineer']
['Rudraksh', 'Jha', 'Detective']
['Varun', 'Bhat', 'Architect']
Data successfully read.
# Write a CSV file:
When we want to write data in a CSV file you have to use writer( ) function. To iterate the data over the rows (lines), you have to use the writerow( ) function.
Code :
import csv
f=open("csvfile.csv", "w")
s = csv.writer(f)
s.writerow(("Aditya", "Kumkar", "Engineer"))
s.writerow(("Panda", "Jha", "Detective"))
s.writerow(("Varun", "Bhat", "Architect"))
print("Data successfully added.")
Output :
Data successfully added.
When we shall open the file in notepad (Flat file) then the contents of the file will look like this:
Aditya,Kumkar,Engineer
Rudraksh,Jha,Detective
Varun,Bhat,Architect