Python CSV File Handling Notes – Class 12 CS (083)
Python CSV File Handling Notes for Class 12 CS (083) covering csv module, CSV file operations, file opening and closing, writer(), writerow(), writerows(), and reader() methods with example programs.
Introduction to CSV
- CSV (Comma Separated Values) is a simple flat file format used to store tabular data.
- It stores numbers and text in plain text format, making it human readable.
- Commonly used for data sharing through spreadsheets and databases.
- Files can be imported/exported in applications like spreadsheets.
- Each line in a CSV file is called a record (row).
- Each record contains fields (values) separated by commas (delimiter).
- Comma is the most commonly used delimiter, but others like tab (\t), colon (:), and semicolon (;) can also be used.
- Data in CSV is stored in a structured tabular form.
Why Use CSV – Advantages
- Helps in handling large and unstructured data by organizing it into structured form.
- Useful for managing huge datasets efficiently.
- Makes data easy to store, process, and transfer.
CSV File Handling in Python
- Python provides a built-in csv module to handle CSV files.
- It is used for reading and writing tabular data.
- The module must be imported before use as:
import csv - The two main operations performed on a CSV file are:
- Reading data from a CSV file
- Writing data to a CSV file
Opening and Closing a CSV File
- A CSV file is opened using Python’s built-in open() function.
- The open() function returns a file object used to perform operations.
- Syntax:
- file_object = open(“file_name.csv”, mode)
- It is usually opened in text mode (r, w, a).
- After opening, this file object is used with the csv module (reader/writer).
Closing a CSV File
- After completing operations, the file should be closed.
- Syntax:
file_object.close() - Closing frees system resources and ensures data is saved properly.
Using ‘with’ open()
- CSV files can also be opened using with open()
- File is automatically closed after the block execution
- No need to explicitly call close()
with open(“file_name.csv”, “r”) as file_object:
# perform operations
Reading from a CSV File – reader()
- Reading from a CSV file is done using the csv.reader() function.
- The file is first opened using Python’s built-in open() function in read mode.
- Reader object is iterable, allowing traversal of the file line by line.
- Each row in the CSV file is returned as a list of field values.
- Data can be accessed one row at a time using the next() function.
Example: Python program to read “student.csv” file contents
import csv
# Opening the file in read mode
f = open(“d:\student.csv”, “r”)
# Creating reader object
csv_reader = csv.reader(f)
# Reading the file record by record
for row in csv_reader:
print(row)
# Closing the file
f.close()
OUTPUT
[‘Name’, ‘ Class’, ‘ Marks’]
[‘Rakesh’, ‘ XII’, ‘ 96’]
[‘Vikas’, ‘ XII’, ‘ 83’]
[‘Amol’, ‘ XII’, ‘ 88’]
Example: Write a program to read the contents of “student.csv” file using ‘with’ open().
# Demonstrate use of with open()
import csv
with open(“student.csv”, ‘r’) as csv_file:
reader = csv.reader(csv_file)
rows = [] # list to store the file data
for rec in reader: # copy data into the list ‘rows’
print(rec)
OUTPUT
[‘Name’, ‘ Class’, ‘ Marks’]
[‘Rakesh’, ‘ XII’, ‘ 96’]
[‘Vikas’, ‘ XII’, ‘ 83’]
[‘Amol’, ‘ XII’, ‘ 88’]
Example: Write a program to count the number of records present in “student.csv” file
# Python program to count the number of records present in “student.csv” file
import csv
f = open(“student.csv”, ‘r’)
csv_reader = csv.reader(f) # csv_reader is the csv reader object
c = 0
# Reading the student file record by record
for row in csv_reader:
c = c + 1
print(“No. of records are:”, c)
f.close() # Explicitly closing the file
OUTPUT
No. of records are: 3
Writing to CSV File – writer(), writerow(), writerows()
- Writing to a CSV file is done using the csv.writer() function.
- The CSV file must be opened using open() in write (‘w’) mode before writing.
- The writer object is used to convert data into a comma-separated format.
- The writerow() method is used to write a single row of data into the CSV file.
(Each row should be given as a list of values) - The writerows() method is used to write multiple rows at once.
- No need to add a newline (\n) manually, as writerow() automatically writes each row on a new line.
- By default, comma (,) is used as a delimiter, but it can be changed if needed.
Example1: without ‘with open()’
import csv
# open file in write mode
f = open(“student.csv”, “w”, newline=”)
# create writer object
writer = csv.writer(f)
# writing data
writer.writerow([“Name”, “Class”, “Marks”])
writer.writerow([“Rinku”, “XII”, 90])
writer.writerow([“Veenu”, “XI”, 88])
# close the file
f.close()
Example: using ‘with open()’
import csv
# opening file in write mode
with open(“student.csv”, “w”, newline=”) as f:
writer = csv.writer(f)
writer.writerow([“Name”, “Class”, “Marks”])
writer.writerow([“Rinku”, “XII”, 90])
writer.writerow([“Veenu”, “XI”, 88])
Example: Program to write student data onto a CSV file
# importing the csv module
import csv
# field names
fields = [‘Name’, ‘Class’, ‘Year’, ‘Percent’]
# data rows of csv file
rows = [
[‘Rohit’, ‘XII’, ‘2003’, ’92’],
[‘Shaurya’, ‘XI’, ‘2004’, ’82’],
[‘Deep’, ‘XII’, ‘2002’, ’80’],
[‘Prerna’, ‘XI’, ‘2006’, ’85’],
[‘Lakshya’, ‘XII’, ‘2005’, ’72’]
]
# name of the csv file
filename = ‘marks.csv’
# writing to csv file
with open(filename, ‘w’, newline=”) as f:
# creating a csv writer object
csv_w = csv.writer(f, delimiter=’,’)
# writing the fields (column headings)
csv_w.writerow(fields)
# writing the data rows
for i in rows:
csv_w.writerow(i)
print(“File Created”)
Example: writing multiple rows using writerows()
import csv
# open file in write mode
f = open(“student.csv”, “w”, newline=”)
# create writer object
writer = csv.writer(f)
#data to be written
data = [
[“Name”, “Class”, “Marks”],
[“Rinku”, “XII”, 90],
[“Veenu”, “XI”, 88],
[“Aman”, “X”, 85]
]
# writing multiple rows at once
writer.writerows(data)
# close the file
f.close()
Output
Name,Class,Marks
Rinku,XII,90
Veenu,XI,88
Aman,X,85