You are on page 1of 1

Python notes:

Exceptions and Files

Exceptions:
o ImportError an import fails
o IndexError a list is indexed with an out-of-range number
o NameError an unknown variable is used
o SyntaxError Code cant be parsed correctly
o TypeError Function is called on a value of an inappropriate type
o ValueError Function is called on a value of the correct type but with a
wrong value
Exception handling
o Try/Except statements where the try block code contains code that
might throw an exception and if that except occurs the try block stops
and the except block runs. If no errors then the except block doesnt
run.
You can use multiple exceptions in the except block using parenthesis
Except statement without any exception specified will catch all errors
Finally statement is used so no matter what errors occur, some code will run.
You can raise exceptions by using raise statement (specify which one)
Exceptions can be raised with arguments that give details about them
Raise statements can be used in except blocks without arguments to re-raise
whatever exception occurred.
Open files to read and write the contents of files
o Use open function
Myfile = open(filename.txt)
o Can use second argument to open fuction
r for read-only mode
w for write mode, for rewriting contents of a file
a append mode, for adding new contents to the end of the file
b opens it in binary mode for non-text files
o Make sure to close files by using close method (file.close())
o You can read a file that has been open in text mode by read method.
o To only read a certain amount of a file you can use numbers in an
argument of the read function so the number of bytes that you want
read is opened.

You might also like