Reading and Writing CSV Files

What is a csv file ?

A CSV is a comma separated values file which allows data to be saved in a table structured format. All CSV files are plain text , can contain numbers and letters only, and structure the data contained within them in a tabular, or table, form.

Sample CSV File Data

The csv module in Python implements classes to operate with CSV files. There are two ways to read a CSV file. You can use the csv module's reader function or you can use the DictReader class.

Usig csv.reader

The csv.reader() method can be used to extract data from a file that contains CSV-formatted data. This method returns a reader object, which can be iterated over to retrieve the lines of your CSV and the data is read as a list of strings.


Every row is returned as an array and can be accessed as such, to print the first cells we could simply write: row[0], row[1], row[2] etc.


Using DictReader class

Python's DictReader class basically creates a CSV object that behaves like a Python OrderedDict . It works by reading in the first line of the CSV and using each comma separated value in this line as a dictionary key. The columns in each subsequent row then behave like dictionary values and can be accessed with the appropriate key.



Writing to CSV Files

The csv module also has two methods that you can use to write a CSV file. You can use the writer function or the DictWriter class. The writer object presents two functions, namely writerow() and writerows() . The difference between them, as you can probably tell from the names, is that the first function will only write one row, and the function writerows() writes several rows at once.

 (C) 2022    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.
SiteMap  | Terms  | About