Class XII: Python Data File Handling 22

Steps to Write data in csv file:

* Import csv module

* Open csv file in a file handle( just as text file)
Example : fh=open(“stu.csv”,”w”)- to open the file in write mode

* Create a writer object by using csv.writer() function.
Ex. stuwriter=csv.writer(fh)

* Obtain user data and form a Python sequence(list or tuple) out of it.
Ex. sturec=(11, ‘Neelam’,79.0)

* Write the Python sequence onto the writer object using csv.writerow() or csv.writerows()
Ex. stuwirter.writerow(sturec)

Reading from a csv file:

Reading a csv file means loading data from csv file and parsing it.

Parsing means loading it in a python iterable and then reading from iterable.

To read from a csv file we need to use csv.reader() function.

It returns a reader object which loads the data from the csv file, removes the delimmiters and returns the data in the form of Python iterable, from where we can fetch one row at a time.

Steps to read data from a csv file:

* Import csv module

* Open csv file in a file handle( just as text file)
Example: fh=open(“stu.csv”,”r”)- to open the file in write mode

* Create a reader object by using csv.reader() function
Example: stureader=csv.reader(fh)

* using for loop fetch the data from the reader object in which data is stored in the form of iterable

Example:
import csv
with open(“student1.csv”,”r”) as fh:
      sreader=csv.reader(fh)
      for rec in sreader:
           print(rec)