0% found this document useful (0 votes)
4 views5 pages

File Handling & Oop in Python

The document covers file handling in Python, detailing operations such as opening, reading, writing, and closing files, along with the use of the 'with' statement for automatic file closure. It also introduces core Object-Oriented Programming concepts including classes, encapsulation, inheritance, polymorphism, and abstraction, providing examples for each. These concepts are essential for writing organized and maintainable code in Python.

Uploaded by

Royal Computers
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views5 pages

File Handling & Oop in Python

The document covers file handling in Python, detailing operations such as opening, reading, writing, and closing files, along with the use of the 'with' statement for automatic file closure. It also introduces core Object-Oriented Programming concepts including classes, encapsulation, inheritance, polymorphism, and abstraction, providing examples for each. These concepts are essential for writing organized and maintainable code in Python.

Uploaded by

Royal Computers
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

File handling in Python involves interacting with files on your computer's storage system.

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]

file = open("my_file.txt", "r") # Opens "my_file.txt" in read mode

 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.

file = open("my_file.txt", "w")


file.write("This is some text.")

 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.

with open("my_file.txt", "r") as file:


content = file.read()
print(content)
Additional operations:

 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")

# Reading from a file


with open("example.txt", "r") as file:
for line in file:
print(line.strip()) #strip removes leading/trailing spaces

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:

1. Classes and Objects:

 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!")

my_dog = Dog("Buddy", "Golden Retriever") # Creating an object


print(my_dog.name) # Accessing attribute
my_dog.bark() # Calling method

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 deposit(self, amount):


self.__balance += amount

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:

 Ability of an object to take on many forms.


 It allows objects of different classes to respond to the same method call in their own way.
 Achieved through method overriding and method overloading.

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

shapes = [Circle(5), Square(4)]


for shape in shapes:
print(shape.area())

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.

from abc import ABC, abstractmethod

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.

AI responses may include mistakes.


[1] https://www.scribd.com/document/430076818/12-OOPS-in-Python
[-] https://itdic1.com/python/python-for-absolute-beginners/
[-] https://www.cnblogs.com/superhin/p/17754793.html
[-] https://pythonjp.ikitai.net/entry/2024/01/17/140000

You might also like