Show Menu

File Handling and Error Handling in Python Cheat Sheet (DRAFT) by

Cheat sheet for file handling and error handling.

This is a draft cheat sheet. It is a work in progress and is not finished yet.

File Handling in Python

File Handling In Python :
It allows you to read and write files, which can be in any format such as text, CSV, JSON, or binary.
Python provides built-in functions to perform file handling operations such as opening, reading, writing, and closing a file.
Opening a file:
file = open("f­ile­nam­e.t­xt", "­r")
Reading a file:
content = file.r­ead()
Writing to a file:
file.w­rit­e("H­ello, world!­")
Closing a file:

Error Handling In Python

Common Error types
n Python, errors are also called except­ions, and they are raised when the program encounters an unexpected condition or situation that it cannot handle.
print "­Hello World!­" # missing parent­hesis
print(x) # variable x is not defined
print(­"­5" + 5) # concat­enation of string and integer
my_list = [1, 2, 3]
print(­my_­lis­t[3]) # index 3 is out of range
int("he­llo­") # cannot convert string to integer
my_dict = {"a": 1, "­b": 2, "­c": 3}
print(my_dict["d"]) # key "­d" not found in dictionary
print(5/0) # division by zero