CSV Files
CSV Files
A CSV file (Comma Separated Values file) is a type of plain text file that uses specific structuring to arrange
tabular data. Because it’s a plain text file, it can contain only actual text data as ASCII or Unicode characters.
The structure of a CSV file is given away by its name. Normally, CSV files use a comma to separate each specific
data value.
CSV files are normally created by programs that handle large amounts of data. They are a convenient way to
export data from spreadsheets and databases as well as import or use it in other programs.
CSV files are very easy to work with programmatically. Any language that supports text file input and string
manipulation (like Python) can work with CSV files directly.
Data is stored in rows and columns or tabular form. Thus it is easy to export from database or spreadsheets.
The csv library provides functionality to both read from and write to CSV files. Designed to work out of the box
with Excel-generated CSV files, it is easily adapted to work with a variety of CSV formats. The csv library contains
objects and other code to read, write, and process data from and to CSV files.
Advantages of CSV:
1. It is easy to generate.
2. It is human readable and easy to edit.
3. It is faster to handle.
4. It is smaller in size.
5. It is simple to implement and parse.
6. It is processed by almost all existing applications.
Disadvantages of CSV:
A CSV file, which is a “comma separated values” file, allows you to save your data in a table-structured format,
which is useful when you need to manage a large database.
1. To perform read and write operation with CSV file, we must import CSV module.
2. open() function is used to open file, and return file object.
The file access modes ‘r’, ‘w’, ‘a’, ‘r+’, ‘w+’, ‘a+’ is to be used while opening csv files.
Opening / closing CSV file:
An additional argument ‘newline’ can be given in the open() function while opening a CSV file. the
newline argument specifies how Python would handle newline characters while working with CSV files
in different operating systems.
Different operating system stores EOL characters differently.
Note: Additional optional argument as newline=”” (null string or empty string) with file open() will ensure
that no translation of EOL characters takes place.
While working with CSV files, the csv module has to be imported in the program using import csv.
The csv modules provide 2 types of objects or functions to perform read and write operations on CSV file.
To write to a CSV file in Python, csv.writer() is used. The csv.writer() returns a writer object that converts the
user’s data into a delimited string. This string can later be used to write into CSV files.
The writer() object provides the following two methods to write data:
Write a program to write student’s detail (RollNo, Name, Marks) into a CSV file ‘Students1.csv’.
import csv
def WRITE():
F=open(“Students1.csv”, “w”, newline=””) # F=open(“Students1.csv”, “w”)
Swriter=csv.writer(F) # Swriter=csv.writer(F, delimiter=”:”)
Swriter.writerow([‘RNo’, ‘Name’, ‘Marks’]) # To write header
while True:
R=int(input(“Enter Roll No.:”))
N=input(“Enter Name:”)
M=int(input(“Enter Marks:”))
data=[R, N, M]
Swriter.writerow(data)
ch=input(“Enter more records (y/n)?”)
if ch.lower()==’n’:
break
F.close()
WRITE()
OR
import csv
def WRITE():
header=['eno','name','salary']
rows=[
[15,'Anubhav Singh',45000],
[20,'Shivesh Tripathi',55000],
[40,'Abhinav Sagar',62000],
[45,'Dhruv Sharma',48000],
[60,'Aryan Rana',64000],
]
F=open('emp3.csv','w')
Swriter=csv.writer(F)
Swriter.writerow(header) # To write header
for r in rows:
Swriter.writerow(r)
F.close()
WRITE()
In the above example the csv file will be created with the following content:
# Creating CSV file through Python program
# Using writerows() function
import csv
def WRITE():
F=open(“Students1.csv”, “w”, newline=””) # F=open(“Students1.csv”, “w”)
rows=[ ]
Swriter=csv.writer(F) # csv_writer=csv.writer(F, delimiter=”:”)
rows.append([‘RNo’, ‘Name’, ‘Marks’]) # To write header
while True:
R=int(input(“Enter Roll No.:”))
N=input(“Enter Name:”)
M=int(input(“Enter Marks:”))
data=[R, N, M]
rows.append(data)
ch=input(“Enter more records (y/n)?”)
if ch.lower()==’n’:
break
Swriter.writerows(rows)
F.close()
WRITE()
OR
import csv
def WRITE():
header=['eno','name','salary']
rows=[
[15,'Anubhav Singh',45000],
[20,'Shivesh Tripathi',55000],
[40,'Abhinav Sagar',62000],
[45,'Dhruv Sharma',48000],
[60,'Aryan Rana',64000],
]
F=open('emp3.csv','w')
Swriter=csv.writer(F)
Swriter.writerow(header) # To write header
Swriter.writerows(rows)
F.close()
WRITE()
WRITE()
In the above example the CSV file will be created with the following content:
The reader() function takes a file object and returns a csv.reader object that can be used to iterate
over the contents of a CSV file.
Example:
Suppose we have a CSV file named student.csv in the current directory with the following entries.
import csv
def READ():
f=open("student.csv", 'r')
Sreader=csv.reader(f)
for r in Sreader:
print(r)
READ()
In the above example, we are using the csv.reader() function in default mode for CSV files having comma
delimiter.
To read such files, we can pass optional parameters to the csv.reader() function
import csv
f=open("student.csv", 'r')
Sreader=csv.reader(f,delimiter='\t')
for r in reader:
print(r)
Q. Write a function to write and read data from a csv file “Items.csv” consisting of ItemNo, ItemName,
Quantity and Price.
import csv
def WRITE():
F=open(“Items.csv”, “w”, newline=””)
Swriter=csv.writer(F)
Swriter.writerow([‘ItemNo’, ‘ItemName’, ‘Quantity’, ‘Price’])
while True:
INo=int(input(“Enter Item No.:”))
IName=input(“Enter Item Name:”)
Qty=int(input(“Enter Quantity:”))
P=int(input(“Enter Price:”))
data=[INo, IName, Qty, P]
Swriter.writerow(data)
ch=input(“Enter more records (y/n)?”)
if ch.lower()==’n’:
break
F.close()
WRITE()
2)
import csv
def READ():
F=open(“Items.csv”, “r)
Sreader=csv.reader(F)
for r in Sreader:
print(r)
READ()
Q. A CSV file “Countries.csv” contains data in the following order - Country, Capital, Code
Sample of “Countries.csv” is given below:
India, New Delhi, II
US, Washington, UU
Malaysia, Kualampur, MM
France, Paris, FF
Write Python functions to write and read from the CSV file.
1)
import csv
def WRITE():
F=open(“Countries.csv”, “w”, newline=””)
Swriter=csv.writer(F)
Swriter.writerow([‘Country’, ‘Capital’, ‘Code’])
while True:
Co=input(“Enter the Country:”)
Cp=input(“Enter the Capital:”)
Cd=input(“Enter Country Code:”)
data=[Co, Cp, Cd]
Swriter.writerow(data)
ch=input(“Enter more records (y/n)?”)
if ch.lower()==’n’:
break
F.close()
WRITE()
2)
import csv
def READ():
F=open(“Countries.csv”, “r)
Sreader=csv.reader(F)
for r in Sreader:
print(r)
READ()
Q. Write a function to write to the file “Product.csv” with the data given below.
The first record of the file should be PID, PName, Cost, quantity
Sample of Product.csv is given below:
[P1, Brush, 50, 200]
[P2, Toothpaste, 120, 150]
import csv
def WRITE():
F=open(“Product.csv”, “w”, newline=””)
Swriter=csv.writer(F)
Swriter.writerow([‘PID’, ‘PName’, ‘Cost’, ‘Quantity’])
while True:
ID=input(“Enter Product ID:”)
Name=input(“Enter Product Name:”)
C=int(input(“Enter Product Cost:”))
Qty=int(input(“Enter Quantity:”))
data=[ID, Name, C, Qty]
Swriter.writerow(data)
ch=input(“Enter more records (y/n)?”)
if ch.lower()==’n’:
break
F.close()
WRITE()