Chapter summary - Unit 3
File I/O: An introduction to file I/O, test files, CSV files, binary files;
Exception Handling: handle a single exception, handle multiple exceptions, Two more skills;
Work with a database: An introduction to relational databases, SQL statements for data
manipulation, SQLite Manager to work with a database, use Python to work with a database
File write modes
- “x” - Create - will create a file, returns an error if the file exist
- “a” - Append - will create a file if the specified file does not exist
- “w” - Write - will create a file if the specified file does not exist
| |
This will create a file object, and operations can be made from the folllowing file object.
Working with csv files
- Writing to a csv file
- import csv module
- obtain the writer object
| |
- write data to the csv file
| |
- Reading from a csv file
- import csv module
- ontain the reader onject
| |
- read data using the reader obbject
- Example of working with a simple csv file
Output
- Example of working with a csv files with fields
| |
Output
- Example of reading from a csv file
Output
- Example of working with binary files in python
Binary files can be opened with the pickle module
Exception handling in python
Whenever an error is occured any program spits out an error message and genrally terminates the program. With exception hadling in python, the interpretor manages the error in a specific way and enables the user to handle the exception in a custom manner.
Exception handling in python
This error code can be also written in this way to specify the custom error.
Here type error is a custom error, this can be replaced by the following errors.
- Raising an exception in python
A standard exception in python can be raised whenever a condition is met
- Use of finally in python The finally clause is executed regardless of whether or not an exception occurs in the try block. The finally clause is often used to close files or free up resources.
Here is an example of how to use the finally clause with the try…except statement:
SQLite with Python
SQLite is a lightweight, embedded relational database management system (RDBMS) that is included in the Python standard library. It is a popular choice for storing small to medium-sized amounts of data, and it is often used in web applications, desktop applications, and scientific computing.
To use SQLite with Python, you can import the sqlite3 module. This module provides a simple API for creating, connecting to, and querying SQLite databases.
Here is an example of how to create a new SQLite database and add a row to it:
| |
You can also use the sqlite3 module to query SQLite databases. Here is an example of how to select all rows from the my_table table:
| |
Operations in SQlite
- Fetchall - Fetches all the rows and columns as a array
- Fetchone - Fetches one line in the form of a string (recursive call needed)
- Commit - Commit the saves
- Execute - Runs the command in the command script