Reading-Notes

View the Project on GitHub MohammadAl-khatib/Reading-Notes

FileIO & Exceptions

Read & Write Files in Python

File is a container for data, most modern files are composed of 3 main parts:

For opening a file use open(file path), it is important to close the file after finishing working on it, this can be ensured by using try and finally or using with open().

open built in function may have some arguments optionally after the path, which define the way you open the file with, here is a quick description of these arguments:

Argument Description
r read only (the default value)
w writing
b binary mode

There are 3 types of files:

  1. Text Files
  2. Buffered Binary Files
  3. Raw File

You can read and write to a file, for detailed coding visit this page

Exceptions in Python

Exceptions result from errors after parsing syntactically right, there are different types of errors in Python.

Using try and except you can target what happens when a specific exception takes place by defining the exception name after except, or leave it empty to target any exception in try block.

This try and except can be followed by else for execution in case of no errors happened in try block, also finally can be used to execute a block of code no matter what happens during the execution of try block.