CSV Files in Python – Import CSV, Open, Close csv, read-write csv using csv.reader and csv.writerow article is mainly focused on CSV file operations in Python using CSV module. This article helps to CBSE class 12 Computer Science students for learning the concepts. So here we go!!
Topics Covered
The CSV module
As you know python module is a .py file with code that defines various classes, functions, and variables in python. A python module can be added to any program later using the import keyword. For more details about the python module refer python documentation.
The CSV module is also one of them.
import csv module
To import csv module you can use any one of the following syntax:
import csv
from csv import writerow
from csv import writerow, reader
from csv import *
In above statements, first example is used to import the complete csv module therefore you can access anything from the module using csv and .(dot) symbol.
In second syntax it won’t access the complete code, it will just allow to use writerow() function only in your program. In next part two functions used from the module and last all the classes, functions and variables can be access using *.
Note: To save the memory and reduce the program size third syntax can be used for your project with a number of required functions only.
Functions of CSV module
As per the syllabus of class 12, we will discuss open(), close(), reader() and writerow() functions in this article. I have already given brief introduction about open() and close() functions in this articles, if you missed them, click one below links and get familiar with them:
The reader() function
The reader() function is used to read the data from CSV file. The syntax of reader() function is as following:
csv.reader
(csvfile, dialect=’excel’, **fmtparams)
Where
csvfile – is the path of CSV file which is going to be read.
dialect – It is used to set a specific parameters like delimiter, single/double quotes or a space
**fmtparams – These are keyword arguments and can be used as per the need of the program
Let’s have a look at the following code:
from csv import reader
def f_CSVread():
f = open("ICCtop5.csv","r")
dt = reader(f)
data = list(dt)
f.close()
print(data)
f_CSVread()
Explanation:
In the above code, I have created one CSV file named ICCtop5.csv.
Line 1: The stepts As I am going to read data only therefore I have written the import statement with from csv import reader statement.
Line 2: It is a function header defines a function f_CSVread().
Line 3: f is defined as file object to open the CSV file with “r” mode.
Line 4: In this line dt is an object which stores data in from CSV file using reader() function.
Line 5: By default read() function returns object from CSV file not the actual data. So actual data is stored in data named list object using list() conversion method.
Line 6: This statement close the file to avoid any conflict in future.
Line 7: This statement prints the output eventually.
Line 8: The function is called to execute the program.
Output:
Display data in proper format
Observe the following code:
from csv import reader
def f_CSVread():
f = open("ICCtop5.csv","r")
dt = reader(f)
data = list(dt)
f.close()
for i in data:
print(i)
f_CSVread()
To print the data in proper format for loop can be used. In the above code, I have used for loop and traverse data from the list.
Output
Yet the output is displayed according to the list. To get it more clear and concise format we have to use another for loop to traverse the values separately. Observe this code:
from csv import reader
def f_CSVread():
f = open("ICCtop5.csv","r")
dt = reader(f)
data = list(dt)
f.close()
for i in data:
for j in i:
print('\t|',j,end=" ")
print()
f_CSVread()
In the above code I have used nested loop to print each value separately from the list and formatted using ‘\t\‘ hence the output looks like as following:
Displaying output without list object
Observe the below-given code where list object is not used to store data read from CSV file:
from csv import reader
def f_CSVread():
f = open("ICCtop5.csv","r")
dt = reader(f)
for i in dt:
for j in i:
print('\t|',j,end="")
print()
f.close()
f_CSVread()
The writerow() function
The writerow() function is used to write data in CSV file.
Creating header row and CSV file
When we are writing data into CSV file we have to create a header row first. Follow the below given steps to write a header row.
Observe the following code which creates a CSV file and creates one object to write a header row in CSV file. Here I have used writer() function to feed data and writerow() function to insert values into a row.
from csv import writer
def f_CSVwrite():
f = open("ICCtop5.csv","w")
dt = writer(f)
dt.writerow(['Rank','Batsman','Team','Rating'])
f.close()
f_CSVwrite()
Inserting data into CSV file
You can insert single row or multiple rows together in CSV file. Let’s have a look at both.
Insert a single row at a time
If you have already created a header row then you have to use append mode to insert data. Observe the following code:
from csv import writer
def f_CSVwrite():
f = open("ICCtop5.csv","a")
r = int(input("Enter rank:"))
b = input("Enter batsman name:")
t = input("Enter team of the player:")
rt = int(input("Enter rating:"))
dt = writer(f)
dt.writerow([r,b,t,rt])
print("Record has been added.")
f.close()
f_CSVwrite()
Input through Python interpreter
Data stored in CSV
Insert multiple rows at a time
To insert multiple rows use while loop inside the function and use validation to stop the input by the user. For validation, I have used a string variable to check user want to restrict the data entry or want to continue. Observe the following code I have done the same.
from csv import writer
def f_CSVwrite():
f = open("ICCtop5.csv","a")
dt = writer(f)
while True:
r = int(input("Enter rank:"))
b = input("Enter batsman name:")
t = input("Enter team of the player:")
rt = int(input("Enter rating:"))
dt.writerow([r,b,t,rt])
print("Record has been added.")
print("Want to add more record?Type YES!!!")
ch = input()
ch = ch.upper()
if ch=="YES":
print("*************************")
else:
break
f.close()
f_CSVwrite()
Python interpreter screen
Data stored in CSV
Now when you insert a row using this method it will add a blank row by default before each new record. You can specify the newline character into an open function to avoid this. To solve this problem I have used the following code:
from csv import writer
def f_CSVwrite():
f = open("ICCtop5.csv","a",newline="\n")
dt = writer(f)
while True:
r = int(input("Enter rank:"))
b = input("Enter batsman name:")
t = input("Enter team of the player:")
rt = int(input("Enter rating:"))
dt.writerow([r,b,t,rt])
print("Record has been added.")
print("Want to add more record?Type YES!!!")
ch = input()
ch = ch.upper()
if ch=="YES":
print("*************************")
else:
break
f.close()
f_CSVwrite()
Python interpreter input
Output in CSV File
Use of quotechar and quoting parameter
Sometimes we are using quotes to enclose the data like dates and text values in MySQL. To accept those kinds of data directly we can use quotechar and quoting parameter in writer()/writerow() function.
quoting parameter values
- csv.QUOTE_MINIMAL: It by default case, it will apply quotes to the field s only they contain the delimiter or quote character
- csv.QUOTE_ALL: Quote all fields
- csv.QUOTE_NONNUMERIC: It applies data like MySQL form where strings and dates enclosed with quotes except numeric data
- csv.QUOTE_NONE: Ignores the values to quote, when this value is passed in writerow() function you must specify the escapechar
Apply this code where you have used writer() function the code:
dt = writer(f,quotechar="'",quoting=csv.NONNUMERIC)
Use of delimiter
When you need to store data which can be separated through any other character except ,(comma) you can use delimiter parameter in writer()/writerow() function.
Write code like this where you have written writer()/writerow() function:
dt = writer(f,delimiter="@")
When you write or use this method excel will display your data into single column only. Because CSV accepts only comma to separate values in excel.
Thank you for reading this article, I hope you learn something from this article. If you have any doubts or query reply us in comment section. Like and share this article to your friends and classmates to understand the concept.
Don’t forget to give your feedback by filling up the following form: