Module 4 Important Questions With Answers
Module 4 Important Questions With Answers
Programs
1. Develop a program to backing up a given Folder (Folder in a current
working directory) into a ZIP File by using relevant modules and
suitable methods.
1. Explain permanent delete and safe delete with a suitable Python
programming example to each.
Permanent delete
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.
import os
from pathlib import Path
for filename in Path.home().glob('*.rxt'):
os.unlink(filename)
Safe delete
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
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.
>>> import send2trash
>>> baconFile = open('bacon.txt', 'a') # creates the file
>>> baconFile.write('Bacon is not a vegetable.')
25
>>> baconFile.close()
>>> send2trash.send2trash('bacon.txt')
2. Explain the role of Assertions in Python with a suitable program.
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.
>>> ages = [26, 57, 92, 54, 22, 15, 17, 80, 47, 73]
>>> ages.sort()
>>> ages
[15, 17, 22, 26, 47, 54, 57, 73, 80, 92]
>>> assert ages[0] <= ages[-1] # Assert that the first age is <= the last age.
The assert statement here asserts that the first item in ages should be less than or equal to
the last one. This is a sanity check; code in sort() is bug-free and did its job, then the assertion
would be true.
>>> ages = [26, 57, 92, 54, 22, 15, 17, 80, 47, 73]
>>> ages.reverse()
>>> ages
[73, 47, 80, 17, 15, 22, 54, 92, 57, 26]
>>> assert ages[0] <= ages[-1] # Assert that the first age is <= the last age.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
(iii) shutil.rmtree():
Since Python’s built-in shutil.rmtree() function irreversibly deletes
files and folders, it can be dangerous to use. The shutil. rmtree(path)
function is used to remove a directory and all of its contents,
including all subdirectories and files.
Calling shutil.rmtree(path) will remove the folder at path, and all
files and folders it contains will also be deleted.