0% found this document useful (0 votes)
9 views

Mod 4 Solutions

The document provides an overview of various Python programming concepts including file deletion methods, assertions, and logging. It explains the use of the shutil module for file operations, the importance of assertions for sanity checks, and the logging module for tracking program execution. Additionally, it discusses the benefits of file compression and differences between shutil.copy() and shutil.copytree().

Uploaded by

meghashreecsiot
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Mod 4 Solutions

The document provides an overview of various Python programming concepts including file deletion methods, assertions, and logging. It explains the use of the shutil module for file operations, the importance of assertions for sanity checks, and the logging module for tracking program execution. Additionally, it discusses the benefits of file compression and differences between shutil.copy() and shutil.copytree().

Uploaded by

meghashreecsiot
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

MOD 4 Introduction to Python Programming (BPLCK105B)

MODULE -4

VTU Questions Paper Solution

1. Explain permanent delete and safe delete with a suitable Python programming
example to each. (8M)

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.
➢ 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.
EX:
import os
for filename in os.listdir():
if filename.endswith('.rxt'):
os.unlink(filename)
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
 Using send2trash is much safer than Python’s regular delete functions, because it will
send folders and files to your computer’s trash or recycle bin instead of permanently
deleting them.
Ex:
> import send2trash
>>> baconFile = open('bacon.txt', 'a') # creates the file
>>> baconFile.write('Bacon is not a vegetable.')

Meghashree, CSE (ICSB) PA College of Engineering Page 1


MOD 4 Introduction to Python Programming (BPLCK105B)

25
>>> baconFile.close()
>>> send2trash.send2trash('bacon.txt')

2. Explain the role of Assertions in Python with a suitable program.


(6 M)
 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

Ex:

x = -10
assert x > 0, "x should be positive"
print("Assertion passed!")
Output :AssertionError: x should be positive

What it does:

 The assert checks if x > 0.


 Since x is 10, the condition is True, so the program prints Assertion passed!.
 If x were negative or zero, it would raise an error like this: AssertionError: x should be
positive

Meghashree, CSE (ICSB) PA College of Engineering Page 2


MOD 4 Introduction to Python Programming (BPLCK105B)

3. Explain the functions with examples: (i) shutil.copytree() (ii) shutil.move() (iii)
shutil.rmtree(). (6M)
i. shutil.copytree()
 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
 The shutil.copytree() call creates a new folder named bacon_backup with the same
content as the original bacon folder
 For Example
>>> import shutil, os
>>> os.chdir('C:\\')
>>> shutil.copytree('C:\\bacon', 'C:\\bacon_backup')
'C: \\bacon_backup'
ii. shutil.move()
 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.
>>> 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.”.
iii. shutil.rmtree().
 Calling shutil.rmtree(path) will remove the folder at path, and all files and folders it
contains will also be deleted.
 Ex:
import shutil
import os
os.mkdir("my_folder")
shutil.rmtree("my_folder")
print("Folder deleted successfully!")

Meghashree, CSE (ICSB) PA College of Engineering Page 3


MOD 4 Introduction to Python Programming (BPLCK105B)

4. Explain the support for Logging with logging module in Python.(8M)


 Logging is a great way to understand what’s happening in your program and in what
order its happening.
 Python’s logging module makes it easy to create a record of custom messages that you
write.
 These log messages will describe when the program execution has reached the logging
function call and list any variables you have specified at that point in time.
 On the other hand, a missing log message indicates a part of the code was skipped and
never executed
 Using the logging Module
 To enable the logging module to display log messages on your screen as your program
runs,
import logging
logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s
- %(message)s')
 when Python logs an event, it creates a LogRecord object that holds information about
that event
 The logging module’s basicConfig() function lets you specify what details about the
LogRecord object you want to see and how you want those details displayed
 EX:
import logging
logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s -
%(message)s')
logging.debug("This is a debug message.")
logging.info("This is an info message.")
logging.warning("This is a warning message.")
Output:
2025-01-07 14:30:10,123 - DEBUG - This is a debug message.
2025-01-07 14:30:10,123 - INFO - This is an info message.
2025-01-07 14:30:10,123 - WARNING - This is a warning message.

Meghashree, CSE (ICSB) PA College of Engineering Page 4


MOD 4 Introduction to Python Programming (BPLCK105B)

5. List out the benefits of compressing file?Also explain reading of a zip file with an
example(8M)
 Compressing a file reduces its size, which is useful when transferring it over the
Internet.
 This single file, called an archive file, can then be, say, attached to an email

1. Saves Storage Space

 Reduces file sizes, freeing up valuable disk or cloud storage.Ueful for archiving large
files like documents, media, or backups.

2. Faster File Transfer

 Smaller files take less time to upload, download, or send over networks.Ideal for
sharing files via email, cloud, or messaging apps.

Reading ZIP Files

 To read the contents of a ZIP file, 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
Ex:
>>> 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']

Meghashree, CSE (ICSB) PA College of Engineering Page 5


MOD 4 Introduction to Python Programming (BPLCK105B)

6. List out the difference between shutil.copy() and shutil.copytree() method


(6M)

Aspect shutil.copy() shutil.copytree()

Functionality Copies a single file. Copies an entire folder and its contents.

Keeps the file name if the destination is


Creates a new folder at the destination
Destination a folder.
with the same name and structure as the
Behavior - Can rename the copied file if the
source folder.
destination includes a filename.
Path of the newly created folder as a
Return Value Path of the copied file as a string.
string.
Copies only one file at a time.Not
Copies entire directories with all
Copying Scope suitable for copying multiple files or
subfolders and files.
directories.

import shutil
import shutil
# Copying a file (spam.txt) to a folder
# Copying an entire folder (bacon) to a
Example Usage (delicious)
new folder (bacon_backup)
shutil.copy('spam.txt', 'delicious')
shutil.copytree('bacon', 'bacon_backup')

7. Breifly Explain assertions and raise a exception (6M)


 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

Ex:

x = -10
assert x > 0, "x should be positive"

Meghashree, CSE (ICSB) PA College of Engineering Page 6


MOD 4 Introduction to Python Programming (BPLCK105B)

print("Assertion passed!")
Output :AssertionError: x should be positive

raise a exception

 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 example

raise Exception('This is the error message.')

Traceback (most recent call last):

File "<pyshell#191>", line 1, in<module>

raise Exception('This is the error message.')

Exception: This is the error message

8. Briefly Explain the logging levels

Level Logging Function Description


The lowest level. Used for small details. Typically only useful when
DEBUG logging.debug()
diagnosing problems.
Used to record general events or confirm that things are working at a
INFO logging.info()
certain point in the program.
Indicates a potential problem that doesn’t stop the program from
WARNING logging.warning()
working, but might cause issues later.

ERROR logging.error() Used to record an error that caused the program to fail in some way.

Meghashree, CSE (ICSB) PA College of Engineering Page 7


MOD 4 Introduction to Python Programming (BPLCK105B)

Level Logging Function Description


The highest level. Indicates a fatal error that has caused or is about to
CRITICAL logging.critical()
cause the program to stop.

9. Explain how to disable a logging from a python program

 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)

Meghashree, CSE (ICSB) PA College of Engineering Page 8

You might also like