Cheatography
https://cheatography.com
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("filename.txt", "r") |
Reading a file: |
content = file.read() |
Writing to a file: |
file.write("Hello, world!") |
Closing a file: |
file.close() |
|
|
Error Handling In Python
Common Error types |
n Python, errors are also called exceptions, and they are raised when the program encounters an unexpected condition or situation that it cannot handle. |
SyntaxError |
print "Hello World!" # missing parenthesis |
NameError |
print(x) # variable x is not defined |
TypeError |
print("5" + 5) # concatenation of string and integer |
IndexError |
my_list = [1, 2, 3] print(my_list[3]) # index 3 is out of range |
ValueError |
int("hello") # cannot convert string to integer |
KeyError |
my_dict = {"a": 1, "b": 2, "c": 3} print(my_dict["d"]) # key "d" not found in dictionary |
ZeroDivisionError |
print(5/0) # division by zero |
|
|
|