File Handling & Oop in Python
File Handling & Oop in Python
This
includes creating, reading, writing, and modifying files. Python provides built-in functions to perform
these operations. [1]
Key Operations:
Opening a File: The open() function is used to open a file. It takes the file name and access
mode as arguments. Common access modes include:
o 'r': Read mode (default).
o 'w': Write mode (creates a new file or overwrites an existing one).
o 'a': Append mode (adds data to the end of the file).
o 'x': Exclusive creation mode (creates a new file, fails if the file exists).
o 'r+': Read and modify an existing file from the beginning.
o 'b': Binary mode (used for non-text files). [2]
Reading a File:
o read(): Reads the entire file as a single string.
o readline(): Reads a single line from the file.
o readlines(): Reads all lines from the file and returns them as a list of strings.
content = file.read()
print(content)
Writing to a File:
o write(): Writes a string to the file.
o writelines(): Writes a list of strings to the file.
Closing a File: It's crucial to close files after use to free up system resources. The close()
method is used for this.
file.close()
Using with statement: The with statement automatically closes the file after the block of code
is executed, even if exceptions occur. This is the recommended way to work with files.
Renaming Files: The os module provides the rename() function for renaming files.
Deleting Files: The os module also provides the remove() function for deleting files.
Example:
# Writing to a file
with open("example.txt", "w") as file:
file.write("Hello, this is a test file.\n")
file.write("This is another line.\n")
Note: Always handle potential errors (e.g., file not found) using try...except blocks.
Here are the core Object-Oriented Programming (OOP) concepts in Python, along with examples:
Class: A blueprint for creating objects. It defines the attributes (data) and methods (functions)
that objects of that class will have.
Object: An instance of a class. It's a concrete entity created based on the class's blueprint.
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
print("Woof!")
2. Encapsulation:
Bundling of data (attributes) and methods that operate on that data within a class.
It hides the internal implementation details and protects data from unauthorized access.
Access modifiers (like _ or __ prefixes) are used to control access to attributes.
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute
def get_balance(self):
return self.__balance
account = BankAccount(1000)
account.deposit(500)
print(account.get_balance()) # Accessing through a method
# print(account.__balance) # This would cause an error
3. Inheritance:
Allows a class (child class) to inherit attributes and methods from another class (parent class).
Promotes code reusability and establishes a hierarchical relationship between classes. [1]
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
class Cat(Animal):
def speak(self):
print("Meow!")
class Dog(Animal):
def speak(self):
print("Woof!")
my_cat = Cat("Whiskers")
my_dog = Dog("Buddy")
my_cat.speak()
my_dog.speak()
4. Polymorphism:
class Shape:
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side * self.side
5. Abstraction:
Hiding complex implementation details and showing only essential information to the user.
Abstract classes and methods are used to define a common interface without providing
specific implementations.
class Vehicle(ABC):
@abstractmethod
def start(self):
pass
@abstractmethod
def stop(self):
pass
class Car(Vehicle):
def start(self):
print("Car started")
def stop(self):
print("Car stopped")
my_car = Car()
my_car.start()
These are the fundamental concepts of OOP in Python. They help in writing more organized,
reusable, and maintainable code.