0% found this document useful (0 votes)
2 views11 pages

Python Assignment 03

The document provides an overview of file compression using the ZipFile module, including methods for reading, extracting, and creating ZIP files. It also discusses assertions and exceptions in Python, the shutil module for file management, and concepts of classes and objects. Additionally, it covers logging types, operator overloading, and polymorphism with examples.

Uploaded by

pranavshekarc
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)
2 views11 pages

Python Assignment 03

The document provides an overview of file compression using the ZipFile module, including methods for reading, extracting, and creating ZIP files. It also discusses assertions and exceptions in Python, the shutil module for file management, and concepts of classes and objects. Additionally, it covers logging types, operator overloading, and polymorphism with examples.

Uploaded by

pranavshekarc
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
You are on page 1/ 11

6/18/25, 8:26 PM OneNote

ASSIGNMENT-03
Wednesday, June 18, 2025 PM 7:33

1.Explain the process of compressing files with the ZipFile module.


ANS:➢ Compressing a file reduces its size, which is useful when transferring it over the Internet.
➢ since a ZIP file can also contain multiple files and subfolders, it’s a handy way to package several files into one.
➢ This single file, called an archive file, can then be, say, attached to an email

➢ Reading ZIP Files :


➢ To read the contents of a ZIPfile,first you must create a ZipFile object(note the capital letters Z and F).
➢ ZipFile objects are conceptually similar to the File objects you saw returned by the open() function
➢ They are values through which the program interacts with the file. To create a ZipFile object, call the zipfile.ZipFile()
function
For example
>>> import zipfile.os
>>> os.chdir('C:\\') # move to the folder with example.zip
>>> exampleZip = zipfile.ZipFile('example.zip')
>>> exampleZip.namelist()
['spam.txt','cats/','cats/catnames.txt','cats/zophie.jpg']
>>> spamInfo = exampleZip.getinfo('spam.txt')
>>> spamInfo.file_size
13908
>>> spamInfo.compress_size
3828
>>> 'Compressed file is %sx smaller!' % (round(spamInfo.file_size / spamInfo .compress_size, 2)) 'Compressed file is 3.63x
smaller!'
>>> exampleZip.close()

➢Extracting from ZIP Files:

https://onedrive.live.com/edit.aspx?resid=470D93A974EDE48C!se918ae3ec5864c3eadca27076b80a9ce&migratedtospo=true&wd=target%28Quick Notes.one%7Cae602f84-c49c-415c-a10a-c52072cb1469%2FUnti… 1/11


6/18/25, 8:26 PM OneNote

➢ The extractall() method for ZipFile objects extracts all the files and folders from a ZIP file into the current working
directory.
>>> import zipfile, os
>>> os.chdir('C:\\') # move to the folder with example.zip
>>> exampleZip = zipfile.ZipFile('example.zip')
>>> exampleZip.extractall()
>>> exampleZip.close()

➢Creating and Adding to ZIP Files:


➢ To create your own compressed ZIP files, you must open the ZipFile object in write mode by passing 'w' as the second
argument.
➢ When you pass a path to the write() method of a ZipFile object, Python will compress the file at that path and add it into
the ZIP file.
➢ The write() method’s first argument is a string of the filename to add. ➢ The second argument is the compression type
parameter, which tells the computer what algorithm it should use to compress the files;
>>> import zipfile
>>> newZip = zipfile.ZipFile('new.zip', 'w')
>>> newZip.write('spam.txt', compress_type=zipfile.ZIP_DEFLATED) >>> newZip.close

2.Develop a program to backing up a given folder into a ZipFile..


ANS:
import os
import sys
import pathlib
import zipfile
dirName = input("Enter Directory name that you want to backup : ")
if not os.path.isdir(dirName): print("Directory", dirName, "doesn’t exists")
sys.exit(0)
curDirectory = pathlib.Path(dirName)
with zipfile.ZipFile("myZip.zip", mode="w") as archive:
for file_path in curDirectory.rglob("*"): archive.write(file_path,arcname=file_path.relative_to (curDirectory)) if
os.path.isfile("myZip.zip"):
print("Archive", "myZip.zip", "created successfully")
else:
print("Error in creating zip archive")

3.Briefly explain Assertion and Raising Exception with example.


https://onedrive.live.com/edit.aspx?resid=470D93A974EDE48C!se918ae3ec5864c3eadca27076b80a9ce&migratedtospo=true&wd=target%28Quick Notes.one%7Cae602f84-c49c-415c-a10a-c52072cb1469%2FUnti… 2/11
6/18/25, 8:26 PM OneNote

ANS: ➢ Assertions :
➢ An assertion is a sanity check to make sure your code isn’t doing something obviously wrong.
➢ These sanity checks are performed by assert statements. If the sanity check fails, then an AssertionError exception is raised.

➢ assert statement consists of the following:


➢ The assert keyword
• A condition (that is, an expression that evaluates to True or False)
• A comma
• A string to display when the condition is False
➢ Exceptions :
➢ Python raises an exception whenever it tries to execute invalid code. ➢ Raising an exception is a way of saying, “Stop
running the code in this function and move the program execution to the except statement.” ➢ Exceptions are raised with a
raise statement. In code, a raise statement consists of the following:
➢ The raise keyword
➢A call to the Exception() function
➢ A string with a helpful error message passed to the Exception() function
➢For ex:
import sys
def DivExp(a,b):
assert a>0, "a should be greater than 0"
try:
c = a/b
except ZeroDivisionError:
print("Value of b cannot be zero")
sys.exit(0)
else:
return c
val1 = int(input("Enter a value for a : "))
val2 = int(input("Enter a value for b : "))
val3 = DivExp(val1, val2)
print(val1, "/", val2, "=", val3)
Output:
Enter a value for a : 7
Enter a value for b : 6 7 / 6 = 1.1666666666666667

4. Summarize the organizing files using Shutil module


ANS: ➢ The shutil Module :

https://onedrive.live.com/edit.aspx?resid=470D93A974EDE48C!se918ae3ec5864c3eadca27076b80a9ce&migratedtospo=true&wd=target%28Quick Notes.one%7Cae602f84-c49c-415c-a10a-c52072cb1469%2FUnti… 3/11


6/18/25, 8:26 PM OneNote

➢ The shutil (or shell utilities) module has functions to let you copy, move, rename, and delete files in your Python programs
1.1

1.Copying Files and Folders :


➢ The shutil module provides functions for copying files, as well as entire folders. Calling shutil.copy(source, destination)
will copy the file at the path source to the folder at the path destination.
➢ If destination is a filename, it will be used as the new name of the copied file. This function returns a string of the path of
the copied file. Program:
>>> import shutil, os
>>>os.chdir('C:\\')
u>>>shutil.copy('C:\\spam.txt', 'C:\\delicious')
'C:\\delicious\\spam.txt' >>>shutil.copy('eggs.txt', 'C:\\delicious\\eggs2.txt') 'C:\\delicious\\eggs2.tx

2.Moving and Renaming Files and Folders:


➢ Calling shutil.move(source, destination) will move the file or folder at the path source to the path destination and will return
a string of the absolute path of the new location.
➢ If destination points to a folder, the source file gets moved into destination and keeps its current filename
>>> import shutil
>>> shutil.move('C:\\bacon.txt', 'C:\\eggs')
'C:\\eggs\\bacon.txt'
➢ Assuming a folder named eggs already exists in the C:\ directory, this shutil.move() calls says, “Move C:\bacon.txt into the
folder C:\eggs.”
➢ The destination path can also specify a filename
>>> shutil.move('C:\\bacon.txt', 'C:\\eggs\\new_bacon.txt') 'C:\\eggs\\new_bacon.txt'
➢ Both of the previous examples worked under the assumption that there was a folder eggs in the C:\ directory. But if there is
no eggs folder, then move() will rename bacon.txt to a file named eggs.
>>> shutil.mo 'C:\\eggs'
➢ The folders that make up the destination must already exist, or else Python will throw an exception
>>> shutil.move('spam.txt', 'c:\\does_not_exist\\eggs\\ham')
Traceback (most recent call last):
File "C:\Python34\lib\shutil.py", line 521, in move os.rename(src,real_dst)
FileNotFoundError: [WinError 3] The system cannot find the path specified:
'spam.txt' -> 'c:\\does_not_exist\\eggs\\ham'

3.Permanently Deleting Files and Folders:


➢ You can delete a single file or a single empty folder with functions in the os module, whereas to delete a folder and all of its
contents, you use the shutil module.

https://onedrive.live.com/edit.aspx?resid=470D93A974EDE48C!se918ae3ec5864c3eadca27076b80a9ce&migratedtospo=true&wd=target%28Quick Notes.one%7Cae602f84-c49c-415c-a10a-c52072cb1469%2FUnti… 4/11


6/18/25, 8:26 PM OneNote

➢ Calling os.unlink(path) will delete the file at path. ➢ Calling os.rmdir(path) will delete the folder at path. This folder must
be empty of any files or folders
➢ Calling shutil.rmtree(path) will remove the folder at path, and all files and folders it contains will also be deleted.
import os
for filename in os.listdir():
if filename.endswith('.rxt'):
os.unlink(filename)

4.Safe Deletes with the send2trash Module:


➢ Since Python’s built-in shutil.rmtree() function irreversibly deletes files and folders, it can be dangerous to use
➢ A much better way to delete files and folders is with the third-party send2trash module
➢ You can install this module by running pip install send2trash from a Terminal window
>>> import send2trash
>>> baconFile = open('bacon.txt', 'a') # creates the file
>>> baconFile.write('Bacon is not a vegetable.') 25
>>> baconFile.close()
>>> send2trash.send2trash('bacon.txt')

5. Explain Class and Objects with examples.


ANS: ➢ CLASSES AND OBJECTS:
In Python, classes are used to create user-defined types, which allow you to organize both data and functions. A class acts like
a blueprint for creating objects, and an object is an instance of a class. Let's break this down simply
➢ Key Concepts
1. Class: A blueprint for creating objects.
○ Example: class Point:
2. Object: An instance of a class.
○ Example: p = Point()
➢ Creating a Class:
A class is defined using the class keyword, followed by the class name and a colon. Inside the class, you can define variables
(attributes) and methods (functions).
Here's a simple class:
class Point: """Represents a point in 2D space."""
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"Point({self.x}, {self.y})"

https://onedrive.live.com/edit.aspx?resid=470D93A974EDE48C!se918ae3ec5864c3eadca27076b80a9ce&migratedtospo=true&wd=target%28Quick Notes.one%7Cae602f84-c49c-415c-a10a-c52072cb1469%2FUnti… 5/11


6/18/25, 8:26 PM OneNote

● __init__ is a special method called the constructor, which initializes the object's attributes.
● self.x and self.y are attributes of the Point object representing its coordinates.
➢ Creating an Object :
To create an object from a class, you call the class like a function:
p = Point(3.0, 4.0)
● p is now a Point object with coordinates x = 3.0 and y = 4.0.
Example Output
When you print the object:
print(p)
# Output: Point(3.0, 4.0)
Python tells you the class (Point) and memory location (in hexadecimal).

6. Explain Logging Types


ANS:

Disabling Logging:
➢ The logging.disable() function disables these so that you don’t have to go into your program and remove all the logging
calls by hand.
➢ pass logging.disable() a logging level, and it will suppress all log messages at that level or lower
>>> import logging
>>> logging.basicConfig(level=logging.INFO, format=' %(asctime)s -%(levelname)s - %(message)s')
>>> logging.critical('Critical error! Critical error!')
2015-05-22 11:10:48,054 - CRITICAL - Critical error! Critical error!
>>> logging.disable(logging.CRITICAL)
>>> logging.critical('Critical error! Critical error!')
https://onedrive.live.com/edit.aspx?resid=470D93A974EDE48C!se918ae3ec5864c3eadca27076b80a9ce&migratedtospo=true&wd=target%28Quick Notes.one%7Cae602f84-c49c-415c-a10a-c52072cb1469%2FUnti… 6/11
6/18/25, 8:26 PM OneNote

>>> logging.error('Error! Error!')


➢ Since logging.disable() will disable all messages after it, you will probably want to add it near the import logging line of
code in your program

7. Illustrate Operator Overloading and Polymorphism in Python with an Example.


ANS: ➢ OPERATOR OVERLOADING:
Operator overloading means that you can change how operators (like +, -, *, etc.) work with objects you create in Python. You
can define special methods in your class to specify how operators should behave when used with objects of that class.
For example, you can change what happens when you add two objects of your Time class using the + operator. By defining a
special method for +, Python will know what to do when you use the + operator with Time objects.
Example:
Exercise: Implement the __add__ Method for Point Class
If you have a Point class with x and y coordinates, you might want to add two Point objects together by adding their x and y
coordinates.
Here’s an example:
class Point: def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __str__(self):
return f"Point({self.x}, {self.y})"
point1 = Point(2, 3)
point2 = Point(4, 5)
result = point1 + point2
Output:
Point(6, 8)
➢ POLYMORPHISM
Polymorphism is a concept where a function or method works with different types of data or objects, without needing to be
changed or rewritten for each type.
Here’s an easy way to understand it:
Example:Imagine you have a function that works with strings to count how many times each letter appears. The same function
can work with other data types, like lists, tuples, or even dictionaries, as long as the elements in those data types are
"compatible" (meaning they can be processed in a similar way).
Polymorphism in Action:
1. You write a function that counts elements (like letters in a word or numbers in a list).

https://onedrive.live.com/edit.aspx?resid=470D93A974EDE48C!se918ae3ec5864c3eadca27076b80a9ce&migratedtospo=true&wd=target%28Quick Notes.one%7Cae602f84-c49c-415c-a10a-c52072cb1469%2FUnti… 7/11


6/18/25, 8:26 PM OneNote

2. Instead of writing a new function for every possible type (strings, lists, etc.), the function works for any type that can be
counted or processed in a similar way.
3. This makes your code more reusable, saving time and effort.
def add_elements(sequence):
return sum(sequence)
print(add_elements([1, 2, 3])) # Output: 6
print(add_elements(["a", "b", "c"]))
Output: "abc"

8. Explain Pure Function and Modifiers with examples.


ANS: ➢ PURE FUNCTIONS:
A pure function is a function that:
● Always produces the same output if given the same input.
● Does not change or modify anything outside of the function (like variables, objects, etc.).
In the example you shared, the function takes two time values (like hours, minutes, and seconds) and combines them to return
a new time object without changing the original times.
2. Prototype and Patch: This is a way of solving problems by starting with a simple version of a solution (the prototype) and
then gradually improving it (patching) to handle more complex situations.
In your example:
● Prototype: The first version of the function just adds the times together but doesn't account for when minutes or seconds go
over 60.
● Patch: The improved version fixes this by making sure that if the seconds go over 60, they get carried over into minutes, and
if the minutes go over 60, they get carried over into hours.
def add(x,y):
returnx+y
result1 = add(3, 5)
result2 = add(3, 5)
. ➢ Modifiers:
Modifiers are functions that change something about an object, unlike pure functions which just create new things without
changing anything.
In the example, the function that adds the time values is improved (patched) to handle cases where the total seconds or minutes
exceed 60. This new version is a modifier because it adjusts the time values to make sure they are in a proper format.
So, in simple terms:
● A pure function just calculates and returns something, without changing anything else.
● You can start with a simple solution (the prototype) and make it better by adding fixes (patching).
● A modifier changes something that already exists, like fixing the time format.

https://onedrive.live.com/edit.aspx?resid=470D93A974EDE48C!se918ae3ec5864c3eadca27076b80a9ce&migratedtospo=true&wd=target%28Quick Notes.one%7Cae602f84-c49c-415c-a10a-c52072cb1469%2FUnti… 8/11


6/18/25, 8:26 PM OneNote

9. Develop a program that uses class Student which prompts the user to enter marks in three subjects and
calculates total marks percentage and displays the score card details.
ANS:
class Student:
def init (self, name = "", usn = "", score = [0,0,0,0]):
self.name = name
self.usn = usn
self.score = score
def getMarks(self):
self.name = input("Enter student Name : ")
self.usn = input("Enter student USN : ")
self.score[0] = int(input("Enter marks in Subject 1 : "))
self.score[1] = int(input("Enter marks in Subject 2 : "))
self.score[2] = int(input("Enter marks in Subject 3 : "))
self.score[3] = self.score[0] + self.score[1] + self.score[2]
def display(self):
percentage = self.score[3]/3
spcstr = "=" * 81
print(spcstr)
print("SCORE CARD DETAILS".center(81))
print(spcstr)
print("%15s"%("NAME"),"%12s"%("USN"), "%8s"%"MARKS1","%8s"%"MARKS2","%8s"%"
MARKS3","%8s"%"TOTAL","%12s"%("PERCENTA GE"))
print(spcstr)
print("%15s"%self.name,"%12s"%self.usn, "%8d"%self.score[0],"%8d"%self.
score[1],"%8d"%self.score[2],"%8d"%self.score[3]," %12.2f"%percentage)
print(spcstr)
def main():
s1 = Student()
s1.getMarks()
s1.display()
main()

10. Explain __init__ & __str__ with an example


ANS: ➢ THE INIT METHOD:
The __init__ method is like a constructor in objectoriented programming. It is automatically called when you create a new
object (an instance) of a class. Think of it as the method that "sets up" the object with its initial state.
https://onedrive.live.com/edit.aspx?resid=470D93A974EDE48C!se918ae3ec5864c3eadca27076b80a9ce&migratedtospo=true&wd=target%28Quick Notes.one%7Cae602f84-c49c-415c-a10a-c52072cb1469%2FUnti… 9/11
6/18/25, 8:26 PM OneNote

For example, if you're creating a Time object that has hours, minutes, and seconds, you want to initialize these values when the
object is created
Example: __init__ for a Time class
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
point1 = Point()
point2 = Point(3, 4)
print(point1.x, point1.y) # Output: 0.0
print(point2.x, point2.y) # Output: 3.4

➢ THE str_ METHOD:


The __str__ method is a special method in Python that is used to return a string representation of an object. This string
representation is usually what Python will show you when you print an object.
It’s like telling Python: "Hey, if you want to print this object, here’s how I want it to look!"
Example: __str__ Method for Time Class
Here’s an example: class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
return f"Point({self.x}, {self.y})"
point = Point(3, 4)
print(point)
Output:
Point(3, 4)

https://onedrive.live.com/edit.aspx?resid=470D93A974EDE48C!se918ae3ec5864c3eadca27076b80a9ce&migratedtospo=true&wd=target%28Quick Notes.one%7Cae602f84-c49c-415c-a10a-c52072cb1469%2FUn… 10/11


6/18/25, 8:26 PM OneNote

https://onedrive.live.com/edit.aspx?resid=470D93A974EDE48C!se918ae3ec5864c3eadca27076b80a9ce&migratedtospo=true&wd=target%28Quick Notes.one%7Cae602f84-c49c-415c-a10a-c52072cb1469%2FUn… 11/11

You might also like