0% found this document useful (0 votes)
3 views6 pages

CSV Files in Python

The document provides a comprehensive guide on how to work with CSV files in Python using the csv module, including importing the module, reading from CSV files with the reader() function, and writing to CSV files with the writerow() function. It includes code examples for reading data, displaying it in a formatted way, and inserting both single and multiple rows into a CSV file while addressing common issues like avoiding blank rows. The document emphasizes the importance of proper file handling and user input for data entry.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views6 pages

CSV Files in Python

The document provides a comprehensive guide on how to work with CSV files in Python using the csv module, including importing the module, reading from CSV files with the reader() function, and writing to CSV files with the writerow() function. It includes code examples for reading data, displaying it in a formatted way, and inserting both single and multiple rows into a CSV file while addressing common issues like avoiding blank rows. The document emphasizes the importance of proper file handling and user input for data entry.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

CSV Files in Python – Import CSV, Open, Close csv, read-write csv using csv.reader and csv.

writerow
import csv module
To import csv module we 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 we 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 the 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 project with a
number of required functions only.

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
Code to read data from CSV file:
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: As we are going to read data only therefore we 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:
Code to display data in proper format:
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, we have used for loop
and traverse data from the list.
Output

Here 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. Check 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:
for j in i:
print('\t|',j,end=" ")
print()
f_CSVread()
In the above code we 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


In 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.
Check the following code which creates a CSV file and creates one object to write a header row in
CSV file. Here we 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


We 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 we have already created a header row then we 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
entry for inserting record into csv thorugh python
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, we have used a string variable to check user want to restrict the data entry or
want to continue. Observe the following code we 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
Inserting data into CSV
Data stored in CSV

Data into csv through python


Now when we insert a row using this method it will add a blank row by default before each new
record. We can specify the newline character into an open function to avoid this. To solve this
problem we 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
Avoid blank row in CSV
Output in CSV File

CSV data without blank rows

You might also like