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

Python Module 4

The document explains file and folder management in Python using the shutil module, covering operations like copying, moving, renaming, and deleting files. It also discusses the send2trash module for safer deletions, the zipfile module for compressing files, and the os module for navigating directory trees. Additionally, it addresses exception handling, assertions, and logging in Python for better debugging and program flow tracking.

Uploaded by

yashu21m
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)
1 views14 pages

Python Module 4

The document explains file and folder management in Python using the shutil module, covering operations like copying, moving, renaming, and deleting files. It also discusses the send2trash module for safer deletions, the zipfile module for compressing files, and the os module for navigating directory trees. Additionally, it addresses exception handling, assertions, and logging in Python for better debugging and program flow tracking.

Uploaded by

yashu21m
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/ 14

MODULE 4

1) Explain copying, moving, renaming, and permanently deleting files and folders in Python using
shutil module with suitable examples. (7 Marks)

Python provides the shutil (shell utilities) module to perform operations like copying, moving,
renaming, and deleting files and folders from within a Python program. It also uses the os module
for basic delete functions. These are useful for file system management in automation scripts.

1) Copying Files and Folders

To copy files and folders, Python provides shutil.copy() and shutil.copytree().

a) shutil.copy(source, destination)

This function copies a file from source to destination.

If destination is a folder, file is copied with the same name.

If destination is a filename, the file is copied and renamed.

It returns the path of the copied file.

Example (from module):

import shutil, os

os.chdir('C:\\')

shutil.copy('C:\\spam.txt', 'C:\\delicious')

shutil.copy('eggs.txt', 'C:\\delicious\\eggs2.txt')

Explanation: The first line copies spam.txt into the folder C:\delicious. The second line copies
eggs.txt and renames it as eggs2.txt.

b) shutil.copytree(source_folder, destination_folder)

This function copies the entire folder along with all its subfolders and files.

Example:

shutil.copytree('C:\\bacon', 'C:\\bacon_backup')

Explanation: This creates a new folder bacon_backup containing the same contents as the original
bacon folder.

2) Moving and Renaming Files and Folders


Python uses shutil.move() to move or rename files and folders.

shutil.move(source, destination)

Moves a file or folder to a new location.

If the destination includes a new name, the file is renamed.

Returns the path of the moved file.

Example (from module):

import shutil

shutil.move('C:\\bacon.txt', 'C:\\eggs')

shutil.move('C:\\bacon.txt', 'C:\\eggs\\new_bacon.txt')

Explanation: First line moves bacon.txt into C:\eggs. Second line moves and renames it as
new_bacon.txt.

Error Example (from module):

shutil.move('spam.txt', 'c:\\does_not_exist\\eggs\\ham')

If the destination folders do not exist, Python raises an error:

FileNotFoundError: [WinError 3] The system cannot find the path specified

3) Permanently Deleting Files and Folders

Files and folders can be permanently deleted using both os and shutil.

a) os.unlink(path) – Deletes a single file.

b) os.rmdir(path) – Deletes an empty folder.

c) shutil.rmtree(path) – Deletes a folder and all its content.

Example (from module):

import os

for filename in os.listdir():

if filename.endswith('.rxt'):

os.unlink(filename)

Explanation: This loop checks every file in the current folder and deletes files ending with .rxt using
os.unlink().
4) Safe Delete using send2trash

Python’s built-in delete functions are permanent. To avoid accidental deletion, we can use the
send2trash module.

send2trash.send2trash(path)

Sends the file/folder to Recycle Bin instead of deleting it permanently.

Safer for deleting important files.

Example (from module):

import send2trash

baconFile = open('bacon.txt', 'a')

baconFile.write('Bacon is not a vegetable.')

baconFile.close()

send2trash.send2trash('bacon.txt')

Explanation: This creates bacon.txt, writes data into it, and sends it to the Recycle Bin safely using
send2trash.

Conclusion:

The shutil module provides powerful functions like copy(), copytree(), move(), and rmtree() for
managing files and folders. The os module helps with file/folder deletion, and the send2trash
module offers safer deletion. These tools are essential for organizing and automating file tasks in
Python.

2-Compressing Files with the zipfile Module


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

3.1 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
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()

3.2 Extracting from ZIP Files\


➢ 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()

3.3 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()

3] ✅ Q) Explain in detail the difference between shutil.copy() and shutil.copytree() with example.

Python provides the shutil module to handle high-level file and folder operations such as copying,
moving, and deleting.

🔹 shutil.copy()

shutil.copy(src, dst) is used to copy a single file from the source path to the destination path.
It copies only files, not directories.
If destination is a folder, the file is copied with the original name.
If destination includes a filename, the file is renamed.
It returns the path to the copied file.
File permissions are copied, but not metadata like creation time.

Example:

import shutil, os
os.chdir('C:\\')
shutil.copy('C:\\spam.txt', 'C:\\delicious')
shutil.copy('eggs.txt', 'C:\\delicious\\eggs2.txt')

In the above example, spam.txt is copied into C:\delicious.


The second line copies and renames eggs.txt as eggs2.txt.

🔹 shutil.copytree()

shutil.copytree(src, dst) is used to copy an entire directory (folder), including all its files and
subdirectories.
It performs a recursive copy of the whole folder tree.
The destination directory must not already exist.
It duplicates the entire folder structure into the destination.
Very useful for backup or folder cloning tasks.

Example:
shutil.copytree('C:\\bacon', 'C:\\bacon_backup')

This command copies the entire contents of the bacon folder into bacon_backup.

🔸 Difference between copy() and copytree():

Feature shutil.copy() shutil.copytree()

Used for Files only Entire folders


Recursive No Yes
Destination Can exist Must not exist
Rename support Yes No
Folder support Not supported Fully supported

✅ Conclusion:

Use shutil.copy() for copying individual files.


Use shutil.copytree() for copying complete folders including all contents.
Both are part of the shutil module and are essential for file management in Python.

4. Q) Explain the "Send to Trash" operation in Python with example. (7 Marks)

🔹 Sending Files to Trash in Python


Normally, Python's os.remove() or shutil.rmtree() functions delete files or folders permanently
without moving them to the Recycle Bin.
To safely delete files by moving them to the Recycle Bin/Trash, Python provides the send2trash
module.

🔹 send2trash Module
send2trash sends a file or folder to the system’s Recycle Bin (on Windows) or Trash (on
macOS/Linux).

It does not delete permanently, so files can be recovered later.


Safer than os.unlink() or shutil.rmtree().

🔹 Installing send2trash
If not pre-installed, install using:
pip install send2trash

🔹 Syntax

from send2trash import send2trash


send2trash('filename_or_folder')

🔹 Example:

import send2trash
send2trash.send2trash('bacon.txt')

Explanation:
The file bacon.txt is moved to the Recycle Bin.
It is not deleted permanently.
User can restore the file manually from the Bin.

🔹 Advantages:
Prevents accidental data loss
Gives user a chance to recover files
Works across Windows, macOS, and Linux

✅ Conclusion:
The send2trash module is used to delete files safely by sending them to the Recycle Bin instead of
deleting permanently. This is useful in applications where user data safety is important.

5-Q) Explain the Directory Tree in Python with example. (7 Marks)

🔹 Directory Tree in Python

Python allows users to navigate, list, and work with directory trees using the os module. A directory
tree represents a folder structure — i.e., folders containing files and other subfolders.
To work with directories and files in a tree-like structure, Python uses:
os.getcwd() – returns current working directory
os.chdir(path) – changes the current working directory
os.listdir(path) – lists all files and folders in a directory
os.walk() – generates the full directory tree (all folders, subfolders, files)
🔹 os.walk() – Directory Tree Traversal
os.walk() is the most important function used to traverse a directory tree.
It yields a tuple of three values for each folder in the tree:

1. Folder name (as string)


2. List of subfolder names (as strings)
3. List of filenames in that folder (as strings)

🔹 Example (from module):


import os
for folderName, subfolders, filenames in os.walk('C:\\delicious'):
print('The current folder is ' + folderName)
for subfolder in subfolders:
print('SUBFOLDER OF ' + folderName + ': ' + subfolder)
for filename in filenames:
print('FILE INSIDE ' + folderName + ': '+ filename)
print('')

🔹 Output Sample:

The current folder is C:\delicious


SUBFOLDER OF C:\delicious: cats
SUBFOLDER OF C:\delicious: walnuts
FILE INSIDE C:\delicious: spam.txt

The current folder is C:\delicious\cats


FILE INSIDE C:\delicious\cats: catnames.txt

The current folder is C:\delicious\walnuts


FILE INSIDE C:\delicious\walnuts: walnuts.txt

✅ Conclusion:

Python’s os.walk() helps to scan all folders and files under a directory, making it useful for search,
backup, and automation tasks that need to explore folder trees.

6-1. Raising 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
➢ If there are no try and except statements covering the raise statement that raised the
exception, the program simply crashes and displays the exception’s error message..
Example (From Module 4):

def boxPrint(symbol, width, height):


if len(symbol) != 1:
raise Exception('Symbol must be a single character string.')
if width <= 2:
raise Exception('Width must be greater than 2.')
if height <= 2:
raise Exception('Height must be greater than 2.')

print(symbol * width)
for i in range(height - 2):
print(symbol + (' ' * (width - 2)) + symbol)
print(symbol * width)

🔹 Output:

>>> boxPrint('*', 15, 5)


***************
* *
* *
* *
***************

>>> boxPrint('**', 15, 5)


Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in boxPrint
Exception: Symbol must be a single character string.

7] ) Define Assertion. What does an Assertion statement in Python consist of? Give an example.
🔹 Definition of Assertion:
An assertion is a sanity-check tool used in Python to test if a condition is true. It helps programmers
find mistakes early by testing assumptions made in the program.

🔹 What does an Assertion Statement consist of?


An assertion statement consists of:
assert condition, 'error message'
condition: a boolean expression
'error message': optional string shown if the condition is false
If the condition is True, nothing happens
If the condition is False, Python raises an AssertionError with the message
🔹 Purpose:
Detect bugs early
Used in debugging and testing
Stops the program when invalid logic or values are found

🔹 Example (From Module 4 PDF):


market_2nd = {'ns': 'green', 'ew': 'red'}

def switchLights(intersection):
for key in intersection.keys():
if intersection[key] == 'green':
intersection[key] = 'yellow'
elif intersection[key] == 'yellow':
intersection[key] = 'red'
elif intersection[key] == 'red':
intersection[key] = 'green'
assert 'red' in intersection.values(), 'Neither light is red!' + str(intersection)

print(market_2nd)
switchLights(market_2nd)
print(market_2nd)

🔹 Explanation:
The function switchLights() simulates a traffic signal switch
It changes light: green → yellow → red → green
After switching, it asserts that at least one light is red
If not, it raises AssertionError: Neither light is red! with the current state

🔹 Output:

{'ns': 'green', 'ew': 'red'}


{'ns': 'yellow', 'ew': 'green'}
Traceback (most recent call last):
...
AssertionError: Neither light is red!{'ns': 'yellow', 'ew': 'green'}
✅ Conclusion:

Assertions are used in Python to ensure program correctness. The assert statement verifies that
conditions hold true during execution. If not, an error is raised, preventing further bugs.

8-Logging
➢ 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

import logging
logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s
- %(message)s')
logging.debug('Start of program')
def factorial(n):
logging.debug('Start of factorial(%s%%)' % (n))
total = 1
for i in range(n + 1):
total *= i
logging.debug('i is ' + str(i) + ', total is ' + str(total))
logging.debug('End of factorial(%s%%)' % (n))
return total
print(factorial(5))
logging.debug('End of program')
➢ debug() function will call basicConfig(), and a line of information will be printed.
➢ This information will be in the format we specified in basicConfig() and will include
the messages we passed to debug().
Output:

2015-05-23 16:20:12,664 - DEBUG - Start of program


2015-05-23 16:20:12,664 - DEBUG - Start of factorial(5)
2015-05-23 16:20:12,665 - DEBUG - i is 0, total is 0
2015-05-23 16:20:12,668 - DEBUG - i is 1, total is 0
2015-05-23 16:20:12,670 - DEBUG - i is 2, total is 0
2015-05-23 16:20:12,673 - DEBUG - i is 3, total is 0
2015-05-23 16:20:12,675 - DEBUG - i is 4, total is 0
2015-05-23 16:20:12,678 - DEBUG - i is 5, total is 0
2015-05-23 16:20:12,680 - DEBUG - End of factorial(5)
0
2015-05-23 16:20:12,684 - DEBUG - End of program

9-levels of logging

Logging Levels
➢ Logging levels provide a way to categorize your log messages by importance. There
are five logging levels
➢ Messages can be logged at each level using a different logging function.

Level Logging Function Description


DEBUG logging.debug() The lowest level. Used for small details.
Usually you care about these messages
only when diagnosing problems.
INFO logging.info() Used to record information on general
events in your program or confirm that
things are working at their point in the
WARNING logging. Warning() Used to indicate a potential problem that
doesn’t prevent the program from
working but might do so in the future.

ERROR logging. Error() Used to record an error that caused the


program to fail to do something.
CRITICAL logging. Critical() The highest level. Used to indicate a fatal
error that has caused or is about to cause
the program to stop running entirely.

>>> import logging


>>> logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s -
%(levelname)s - %(message)s')
>>> logging.debug('Some debugging details.')
2015-05-18 19:04:26,901 - DEBUG - Some debugging details.
>>> logging.info('The logging module is working.')
2015-05-18 19:04:35,569 - INFO - The logging module is working.
>>> logging.warning('An error message is about to be logged.')
2015-05-18 19:04:56,843 - WARNING - An error message is about to be
logged.
>>> logging.error('An error has occurred.')
2015-05-18 19:05:07,737 - ERROR - An error has occurred.
>>> logging.critical('The program is unable to recover!')
2015-05-18 19:05:45,794 - CRITICAL - The program is unable to recover!

10-IDLE AND DEBUGG CONTROL WINDOW

IDLE ’s Debugger
➢ The debugger is a feature of IDLE that allows you to execute your program one line
at a time.
➢ The debugger will run a single line of code and then wait for you to tell it to continue
➢ To enable IDLE’s debugger, click Debug4Debugger in the interactive shell window.
➢ When the Debug Control window appears, select all four of the Stack, Locals, Source,
and Globals checkboxes so that the window shows the full set of debug information
➢ While the Debug Control window is displayed, any time you run a program from the
file editor
➢ debugger will pause execution before the first instruction and display the following:
➢ The line of code that is about to be executed
➢ A list of all local variables and their values
➢ A list of all global variables and their values
➢ The program will stay paused until you press one of the five buttons in the Debug
Control window: Go, Step, Over, Out, or Quit.

Go
➢ Clicking the Go button will cause the program to execute normally until it terminates
or reaches a breakpoint
➢ If you are done debugging and want the program to continue normally, click the Go
button.

Step
➢ Clicking the Step button will cause the debugger to execute the next line of code and
then pause again
➢ The Debug Control window’s list of global and local variables will be updated if their
values change.
➢ If the next line of code is a function call, the debugger will “step into” that function
and jump to the first line of code of that function.

Over
➢ Clicking the Over button will execute the next line of code, similar to the Step button.
➢ The Over button will “step over” the code in the function. The function’s code will be
executed at full speed, and the debugger will pause as soon as the function call
returns.
➢ For example, if the next line of code is a print() call, you don’t really care about code
inside the built-in print() function; you just want the string you pass it printed to the
screen.

Quit
➢ If you want to stop debugging entirely and not bother to continue executing the rest of
the program, click the Quit button
➢ The Quit button will immediately terminate the program. If you want to run your
program normally again, select Debug4Debugger again to disable the debugger.

11- Develop a program to sort the contents of a text file and write the sorted contents into a
separate text

import os
importsys
# Prompt the user for the file name
fname = input("Enter the filename whose contents are to be sorted: ")
# Check if the file exists
if not os.path.isfile(fname):
print("File",fname, "doesn't exist.")
sys.exit(0)
# Open the input file and read its contents
with open(fname, "r") as infile:
myList = infile.readlines()
# Remove trailing newline characters and sort the list
lineList = [line.strip() for line in myList]
lineList.sort()
with open("sorted.txt", "w") as outfile:
for line in lineList:
outfile.write(line + '\n')
# Check if the output file was successfully created and print its contents
if os.path.isfile("sorted.txt"):
print("\nFile containing sorted content'sorted.txt' created successfully.")
print("'sorted.txt' contains", len(lineList), "lines.")
print("Contents of 'sorted.txt':")
print("===========================================================")
with open("sorted.txt", "r") asrdFile:
for line in rdFile:
print(line, end="")

output:
Enter the filename whose contents are to be sorted: input.txt
File containing sorted content 'sorted.txt' created successfully.
'sorted.txt' contains 7 lines.
'sorted.txt' contains 7 lines.
===============================

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

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

output: Enter Directory name that you want to backup ; jit


Archive myžip.zip created successfully
13.Write a function named DivExp which takes TWO parameters a, b and returns a value c (c=a/b).
Write suitable assertion for a greater than 0 in function DivExp and raise an exception for when b=0.
Develop a suitable program which reads two values from the console and calls a function DivExp.

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
Enter a value for a: 0
Enter a value for b: 10
AssertionError: a should be greater than 0
Enter a value for a: 1
Enter a value for b: 0
Value of b cannot be zero
13.

You might also like