Python and CSV files

Unit 13 > Computer Science > Class 12 > Samacheer Kalvi - English Medium

Objectives


• Understand what is CSV? • Able to import CSV fi les in python programs • Execute and debug python programs

Summary


• A CSV file is a human readable text file where each line has a number of fields, separated by commas or some other delimiter • Excel is a binary file whereas CSV format is a plain text format • The two ways to read a CSV file are using csv.reader() function and using DictReader class. • The default mode of csv file in reading and writing is text mode • Binary mode can be be used when dealing with non-text files like image or exe files. • Python has a garbage collector to clean up unreferenced objects • close() method will free up the resources that were tied with the file • By default CSV files should open automatically in Excel • The CSV library contains objects and other code to read, write, and process data from and to CSV files. • “skipinitialspace” is used for removing whitespaces after the delimiter • To sort by more than one column operator.itemgetter() can be used • DictReader() class of csv module creates an object which maps data to a dictionary • CSV file having custom delimiter is read with the help of csv.register_dialect(). • To sort by more than one column itemgetter() with multiple indices is used. • csv.reader and csv.writer work with list/tuple, while csv.DictReader and csv.DictWriter work with dictionary . • csv.DictReader and csv.DictWriter take additional argument fieldnames that are used as dictionary keys. • The function dict() is used to print the data in dictionary format without order. • The csv.writer() method returns a writer object which converts the user’s data into delimited strings. • The writerow() method writes one row at a time. Writerows() method is used to write all the data at once • Adding a new row at the end of the file is called appending a row.