Page 140 - PYTHON-12
P. 140
Like other files (text and binary) in Python, there are two basic operations that can be carried out
on a CSV file.
1. Reading a CSV
2. Writing to a CSV.
Let us discuss these CSV operations.
4.15.1 Reading from CSV File
Reading from a CSV file is done using the reader object. The CSV file is opened as a text file with
Python’s built-in open() function, which returns a file object. This creates a special type of object to
access the CSV file (reader object), using the reader() function.
The reader object is an iterable that gives us access to each line of the CSV file as a list of fields. You
can also use next() directly on it to read the next line of the CSV file, or you can treat it like a list in
a for loop to read all the lines of the file (as lists of the file’s fields).
This is shown in the practical implementation given below.
Before this, enter the student details in spreadsheet and save this file as shown:
Next step is to open the Notepad and enter the data for student.csv, which will be the equivalent
for student.xls.
student.csv
student.xls
Python Libraries
4.11