File Handling
File handling refers to the creating, reading, writing and managing files using python.
File Modes
| Mode | Description |
|---|---|
r | Read |
w | Write (overwrite) |
a | Append |
x | Create file |
rb | Read binary |
wb | Write binary |
r+ | Read and write |
Some key point to know
- To read entire file use
f.read()or to read one linef.readline()or to read all linesfile.readlines() - If file mode is used as
wit will overwrite the existing content of the file, to only append the data at the end useafile mode. - Using context manager while dealing with files is recommended.
with open(file, 'w') as fthis syntax.
Exception Handling
Exception Handling is a mechanism used to handle runtime errors and prevent the program from terminating unexpectedly. Exception handling is implemented using try and expect block.
try:
x = 1 / 0
print(x)
expect Exception as e:
print('Diving by zero')
Some important topics to know
1. *args and **kwargs
*args collects positional arguments into a tuple, while **kwargs collects keyword arguments into a dictionary.
def add(*args):
return sum(args)
def employee(**kwargs):
print(kwargs)
print(add(1, 2, 3, 4))
employee(name="Pranjal", role="Data Engineer")
# O/P
# 10
# { 'name': 'Pranjal', 'role': 'Data Engineer' }
2. Decorators
A Decorator is a function that modifies or extends the behavior of another function without changing its source code.
They are helpful for logging, authenticating, monitoring, performance tracking, retry mechanisms
def decorator(func):
def wrapper():
print("Before Function")
func()
print("After Function")
return wrapper
@decorator
def greet():
print("Hello")
greet()
3. @staticmethod vs @classmethod
Static methods are utility functions related to a class which can be called from class itself but cannot access class-level data , while class methods operate on class-level data through the cls parameter.
| Feature | Instance | Static | Class |
|---|---|---|---|
| First Arg | self | None | cls |
| Access Instance Variables | ✅ | ❌ | ❌ |
| Access Class Variables | ✅ | ❌ | ✅ |
| Called By | Object | Class/Object | Class/Object |
5. Multithreading vs Multiprocessing
Multithreading is running multiple threads inside the same process.
Multiprocessing is running multiple independent processes.
In python, only one thread executes python bytecode at a time. Therefore, multithreading does not significantly speed up CPU bound tasks. Multiprocessing bypasses GIL (Global Interpreter Lock) because each process has it's own Python interpreter.