0% found this document useful (0 votes)
17 views14 pages

18 TO 23 Notes

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

18 TO 23 Notes

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT 4: FILES & OBJECT-ORIENTED PROGRAMMING - COMPREHENSIVE GUIDE WITH

EXAMPLES

PART 1: FILE HANDLING IN PYTHON

1.1 Types of Files

- Text Files: Human-readable, store data as strings (`.txt`, `.csv`, `.py`)

- Binary Files: Machine-readable, store data in bytes (`.jpg`, `.pdf`, `.exe`)

1.2 File Operations - Complete Examples

Basic File Modes:

Mode Description Example


'r' Read (default) open('[Link]', 'r')
'w' Write (overwrites) open('[Link]', 'w')
'a' Append open('[Link]', 'a')
'r+' Read + Write open('[Link]', 'r+')
'b' Binary mode open('[Link]', 'rb')

Example 1: Creating and Reading Text Files

```python

# Writing to a file

with open('[Link]', 'w') as file:

fi[Link]("Hello World\n")

fi[Link]("Python Programming\n")

fi[Link]("File Handling Examples\n")

# Reading entire file

with open('[Link]', 'r') as file:

content = fi[Link]()

print("Full Content:")

print(content)
# Reading line by line

with open('[Link]', 'r') as file:

print("\nLine by Line:")

for line in file:

print([Link]())

```

Output:

```

Full Content:

Hello World

Python Programming

File Handling Examples

Line by Line:

Hello World

Python Programming

File Handling Examples

```

1.3 File Methods - Practical Examples

```python

# Demonstrating diberent read methods

with open('[Link]', 'w') as f:

[Link]("Line 1: Apple\nLine 2: Banana\nLine 3: Cherry\n")

with open('[Link]', 'r') as f:

print("read():", repr([Link]())) # Reads entire content


[Link](0) # Reset file pointer

print("readline():", repr([Link]())) # Reads first line

[Link](0)

print("readlines():", [Link]()) # List of all lines

```

Output:

```

read(): 'Line 1: Apple\nLine 2: Banana\nLine 3: Cherry\n'

readline(): 'Line 1: Apple\n'

readlines(): ['Line 1: Apple\n', 'Line 2: Banana\n', 'Line 3: Cherry\n']

```

1.4 Binary Files & Pickle Module - Examples

```python

import pickle

# Example 1: Storing complex data

student_data = {

'name': 'Alice',

'age': 20,

'courses': ['Math', 'Physics', 'Chemistry'],

'grades': {'Math': 85, 'Physics': 90, 'Chemistry': 78}

# Writing binary data


with open('[Link]', 'wb') as file:

[Link](student_data, file)

# Reading binary data

with open('[Link]', 'rb') as file:

loaded_data = [Link](file)

print("Loaded Data:", loaded_data)

# Example 2: Storing multiple objects

data1 = [1, 2, 3, 4, 5]

data2 = {"key": "value", "number": 42}

with open('[Link]', 'wb') as f:

[Link](data1, f)

[Link](data2, f)

with open('[Link]', 'rb') as f:

loaded1 = [Link](f)

loaded2 = [Link](f)

print("First object:", loaded1)

print("Second object:", loaded2)

```

1.5 CSV File Handling - Examples

```python

import csv

# Writing to CSV file


with open('[Link]', 'w', newline='') as file:

writer = [Link](file)

[Link](['Name', 'Age', 'Grade'])

[Link](['Alice', '20', 'A'])

[Link](['Bob', '21', 'B'])

[Link](['Charlie', '19', 'A'])

# Reading from CSV file

print("CSV Content:")

with open('[Link]', 'r') as file:

reader = [Link](file)

for row in reader:

print(row)

# Using DictReader for easier access

print("\nUsing DictReader:")

with open('[Link]', 'r') as file:

reader = [Link](file)

for row in reader:

print(f"{row['Name']} is {row['Age']} years old with grade {row['Grade']}")

```

Output:

```

CSV Content:

['Name', 'Age', 'Grade']

['Alice', '20', 'A']

['Bob', '21', 'B']


['Charlie', '19', 'A']

Using DictReader:

Alice is 20 years old with grade A

Bob is 21 years old with grade B

Charlie is 19 years old with grade A

```

1.6 os and [Link] Modules - Examples

```python

import os

# File operations

print("Current Directory:", [Link]())

print("Files in current directory:", [Link]('.'))

# Check if file exists

if [Link]('[Link]'):

print("[Link] exists")

print("File size:", [Link]('[Link]'), "bytes")

print("Is file?", [Link]file('[Link]'))

print("Is directory?", [Link]('[Link]'))

# Create directory

[Link]('test_folder', exist_ok=True)

print("Created test_folder")

# Join paths safely


file_path = [Link]('test_folder', 'new_fi[Link]')

print("Full path:", file_path)

```

---

PART 2: OBJECT-ORIENTED PROGRAMMING (OOP)

2.1 Basic Class and Object - Example

```python

class Student:

# Class attribute (shared by all instances)

school_name = "ABC High School"

# Constructor method

def __init__(self, name, age, grade):

# Data attributes (instance variables)

[Link] = name

[Link] = age

[Link] = grade

# Method

def display_info(self):

return f"Name: {[Link]}, Age: {[Link]}, Grade: {[Link]}"

# Method to update grade

def update_grade(self, new_grade):

[Link] = new_grade
# Creating objects

student1 = Student("Alice", 20, "A")

student2 = Student("Bob", 21, "B")

print(student1.display_info())

print(student2.display_info())

print("School:", Student.school_name)

student1.update_grade("A+")

print("After update:", student1.display_info())

```

Output:

```

Name: Alice, Age: 20, Grade: A

Name: Bob, Age: 21, Grade: B

School: ABC High School

After update: Name: Alice, Age: 20, Grade: A+

```

2.2 Encapsulation - Example

```python

class BankAccount:

def __init__(self, account_holder, balance=0):

self.account_holder = account_holder

self.__balance = balance # Private attribute


# Public method to access private attribute

def get_balance(self):

return self.__balance

def deposit(self, amount):

if amount > 0:

self.__balance += amount

return f"Deposited ${amount}. New balance: ${self.__balance}"

return "Invalid deposit amount"

def withdraw(self, amount):

if 0 < amount <= self.__balance:

self.__balance -= amount

return f"Withdrew ${amount}. New balance: ${self.__balance}"

return "Insubicient funds or invalid amount"

# Usage

account = BankAccount("John Doe", 1000)

print([Link](500))

print([Link](200))

print("Current balance:", account.get_balance())

# This will cause an error (attribute is private)

# print(account.__balance) # AttributeError

```

Output:

```
Deposited $500. New balance: $1500

Withdrew $200. New balance: $1300

Current balance: 1300

```

2.3 Inheritance - Complete Example

```python

# Parent class

class Vehicle:

def __init__(self, brand, model, year):

[Link] = brand

[Link] = model

[Link] = year

self.__mileage = 0 # Private attribute

def start_engine(self):

return f"{[Link]} {[Link]} engine started"

def stop_engine(self):

return f"{[Link]} {[Link]} engine stopped"

def get_mileage(self):

return self.__mileage

def drive(self, distance):

if distance > 0:

self.__mileage += distance

return f"Drove {distance} miles. Total mileage: {self.__mileage}"


return "Invalid distance"

# Child class 1

class Car(Vehicle):

def __init__(self, brand, model, year, doors):

super().__init__(brand, model, year)

[Link] = doors

# Method overriding

def start_engine(self):

return f"Car {[Link]} {[Link]} vroom vroom!"

def honk(self):

return "Beep beep!"

# Child class 2

class Motorcycle(Vehicle):

def __init__(self, brand, model, year, engine_size):

super().__init__(brand, model, year)

self.engine_size = engine_size

def wheelie(self):

return "Doing a wheelie!"

# Using the classes

car = Car("Toyota", "Camry", 2022, 4)

bike = Motorcycle("Harley", "Davidson", 2021, "1200cc")


print(car.start_engine())

print([Link](50))

print([Link]())

print(bike.start_engine())

print([Link]())

```

Output:

```

Car Toyota Camry vroom vroom!

Drove 50 miles. Total mileage: 50

Beep beep!

Harley Davidson engine started

Doing a wheelie!

```

2.4 Polymorphism - Example

```python

class Circle:

def __init__(self, radius):

[Link] = radius

def area(self):

return 3.14159 * [Link] 2

def perimeter(self):

return 2 * 3.14159 * [Link]


class Rectangle:

def __init__(self, width, height):

[Link] = width

[Link] = height

def area(self):

return [Link] * [Link]

def perimeter(self):

return 2 * ([Link] + [Link])

# Polymorphism in action

shapes = [Circle(5), Rectangle(4, 6)]

for shape in shapes:

print(f"Area: {[Link]():.2f}")

print(f"Perimeter: {[Link]():.2f}")

print("---")

```

Output:

```

Area: 78.54

Perimeter: 31.42

---

Area: 24.00

Perimeter: 20.00
---

```

---

You might also like