Tamilnadu Samacheer Kalvi 12th Computer Science Notes Chapter 13 Python and CSV Files Notes
A CSV file is a human readable text file where each line has a number of fields, separated by commas or some other delimiter
Two ways to read a CSV file:
The two ways to read a CSV file are using csv.reader() function and using DictReader class.
Python File Modes:
|‘r’||Open a file for reading, (default)|
|‘w’||Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.|
|‘x’||Open a file for exclusive creation. If the file already exists, the operation fails.|
|‘a’||Open for appending at the end of the file without truncating it. Creates a new file if it does not exist.|
|‘t’||Open in text mode, (default)|
|‘b’||Open in binary mode.|
|‘+’||Open a file for updating (reading and writing)|
- The default mode of csv file in reading and writing is text mode
- Binary mode can be used when dealing with non-text files like image or exe files.
Python has a garbage collector to clean up unreferenced objects
Skip initial space:
“skip initial space” is used for removing whitespaces after the delimiter
The ŒV library contains objects and other code to read, write, and process data from and to CSV files.
csv.reader, csv.writer,csv.ÐictReader, csv.DictWriter:
- csv.reader and csv.writer work with list/tuple.
- csv.DictReader and csv.Dict Writer work with dictionary.
- csv.DictReader and csv.Dict Writer take additional arguments fieldnames that are used as dictionary keyš.
- The csv.writer() method returns a writet object which converts the user’s data into delimited strings.
- DictReader() class of csv module creates an object which maps data to a dictionary.
operator.itemgetter can be used to sort by more than one column operator.itemgetter()
itemgetter() with multiple indices is used to sort by more than one column.
writerow() Vs Writerows():
The writerowQ method writes one row at a time. WriterowsQ method is used to write all the data at once.
CSV file having custom delimiter is read with the help of csv.register_dialect().
close() method will free up the resources that were tied with the file
A Line Terminator is a string used to terminate lines produced by writer.
A dialect is a class of csv module which helps to define parameters for reading and writing CSV.
An Ordered Diet is a dictionary subclass which saves the order in which its contents are added.