Python Module 4
Python 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.
a) shutil.copy(source, destination)
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.
shutil.move(source, destination)
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.
shutil.move('spam.txt', 'c:\\does_not_exist\\eggs\\ham')
Files and folders can be permanently deleted using both os and shutil.
import os
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)
import send2trash
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.
➢ 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;
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')
🔹 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.
✅ Conclusion:
🔹 send2trash Module
send2trash sends a file or folder to the system’s Recycle Bin (on Windows) or Trash (on
macOS/Linux).
🔹 Installing send2trash
If not pre-installed, install using:
pip install send2trash
🔹 Syntax
🔹 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.
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:
🔹 Output Sample:
✅ 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.
print(symbol * width)
for i in range(height - 2):
print(symbol + (' ' * (width - 2)) + symbol)
print(symbol * width)
🔹 Output:
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.
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:
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.
➢ 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:
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.
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")
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.