0% found this document useful (0 votes)
3 views9 pages

Python Module 4 IMP Questioons

The document provides an overview of the Python `shutil` module, detailing its functions for file operations such as copying, moving, deleting, and archiving files and directories. It also explains the concepts of compressing files, including reading, extracting, and creating ZIP files, as well as the differences between permanent and safe deletion of files. Additionally, it covers assertions, logging, debugging techniques, and their applications in a traffic light simulation.

Uploaded by

ayushgt15
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)
3 views9 pages

Python Module 4 IMP Questioons

The document provides an overview of the Python `shutil` module, detailing its functions for file operations such as copying, moving, deleting, and archiving files and directories. It also explains the concepts of compressing files, including reading, extracting, and creating ZIP files, as well as the differences between permanent and safe deletion of files. Additionally, it covers assertions, logging, debugging techniques, and their applications in a traffic light simulation.

Uploaded by

ayushgt15
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/ 9

MODULE 4

1. Explain all the functions of Shutil Module with programming examples

A: The `shutil` module in Python provides a high-level interface for file operations, including copying, moving, and
deleting files and directories. Here's an explanation of some of its main functions along with programming examples:

1. shutil.copy(src, dst): Copies the file `src` to the file or directory `dst`.

Example

import shutil

# Copy a file

shutil.copy('source.txt', 'destination.txt')

# Copy a file into a directory

shutil.copy('source.txt', 'destination_folder/')

2. shutil.copy2(src, dst): Similar to `copy()`, but also attempts to preserve the metadata of the original file.

Example

import shutil

# Copy a file while preserving metadata

shutil.copy2('source.txt', 'destination.txt')

3. shutil.copyfile(src, dst): Copies the contents of the file `src` to file `dst`. The destination file is overwritten if it
exists.

Example

import shutil

# Copy contents of a file to another

shutil.copyfile('source.txt', 'destination.txt')

4. shutil.move(src, dst): Moves the file or directory `src` to `dst`.

Example

import shutil

# Move a file

shutil.move('source.txt', 'destination.txt')

# Move a directory

shutil.move('source_folder/', 'destination_folder/')

5. shutil.rmtree(path): Deletes a directory and all its contents recursively.

Example
import shutil

# Delete a directory and its contents

shutil.rmtree('directory_to_delete/')

6. shutil.make_archive(base_name, format, root_dir): Creates an archive (e.g., zip, tar) containing the contents of
the directory `root_dir`.

Example

import shutil

# Create a zip archive of a directory

shutil.make_archive('archive', 'zip', 'directory_to_archive/')

7. shutil.unpack_archive(filename, extract_dir): Extracts the contents of an archive file into the directory
`extract_dir`.

Example

import shutil

# Extract contents of a zip archive

shutil.unpack_archive('archive.zip', 'extracted_contents/')

2. What are the different methods of file operations supported in the python shutil module.

A: The `shutil` module in Python provides several methods for file operations, primarily focused on high-level file and
directory manipulation. Here are the main methods supported by the `shutil` module:

1. Copying Files and Directories:


• shutil.copy(src, dst): Copy a file `src` to `dst`.
• shutil.copy2(src, dst): Copy a file and try to preserve metadata.
• shutil.copyfile(src, dst): Copy the contents of a file `src` to `dst`.
• shutil.copytree(src, dst): Recursively copy an entire directory tree rooted at `src` to `dst`.

2. Moving or Renaming Files and Directories:


• shutil.move(src, dst): Move a file or directory `src` to `dst`.

3. Deleting Files and Directories:


• shutil.rmtree(path): Recursively delete a directory tree rooted at `path`.

4. Archiving and Extracting Files:


• shutil.make_archive(base_name, format, root_dir): Create an archive file (e.g., zip, tar) from `root_dir`.
• shutil.unpack_archive(filename, extract_dir): Extract the contents of an archive file into `extract_dir`.
3. What is meant by compressing files? Explain reading, extracting and creating ZIP files with programming examples for
each

A: Compressing files refers to reducing their size by encoding the data in a more efficient manner, typically resulting in a
smaller file size. This can be achieved using various compression algorithms, one common method being ZIP compression.
ZIP is a popular file format used for compressing and archiving files and directories.

Here's an explanation of reading, extracting, and creating ZIP files with programming examples for each:

1. Reading ZIP Files:

To read the contents of a ZIP file in Python, you can use the `zipfile` module. The following example demonstrates how to
read the contents of a ZIP file:

Example

import zipfile

# Open the ZIP file in read mode

with zipfile.ZipFile('example.zip', 'r') as zip_ref:

# List the contents of the ZIP file

zip_ref.printdir()

# Extract a specific file from the ZIP file

zip_ref.extract('file_inside_zip.txt', 'extracted_files/')

2. Extracting ZIP Files:

To extract the contents of a ZIP file, you can use the `extractall()` method of the `ZipFile` object. Here's an example:

Example

import zipfile

# Open the ZIP file in read mode

with zipfile.ZipFile('example.zip', 'r') as zip_ref:

# Extract all contents of the ZIP file into a directory

zip_ref.extractall('extracted_files/')

3. Creating ZIP Files:

To create a new ZIP file or add files to an existing one, you can use the `ZipFile` class in the `zipfile` module. Here's an
example:

Example

import zipfile
# Create a new ZIP file
with zipfile.ZipFile('new_archive.zip', 'w') as zip_ref:
# Add a single file to the ZIP file
zip_ref.write('file1.txt')
# Add multiple files to the ZIP file
zip_ref.write('file2.txt')
zip_ref.write('file3.txt')
4. Explain the differences between permanent delete and safe delete with suitable Python programming examples to
each.
A: Permanent delete and safe delete are two different approaches to deleting files or directories in a file system.
1. Permanent Delete:
• Permanent delete refers to the action of removing a file or directory from the file system without the possibility
of recovery. Once a file or directory is permanently deleted, it cannot be easily restored using standard
methods. This action is irreversible and typically involves removing the file's data from the storage device.

2. Safe Delete:
• Safe delete, also known as soft delete or trash/delete to recycle bin, involves moving the file or directory to a
designated location (e.g., recycle bin, trash folder) instead of immediately removing it from the file system. This
allows for the possibility of recovering the deleted item if needed. Safe delete provides a safeguard against
accidental deletion and offers a chance for users to restore deleted files or directories.

Here are Python programming examples for each approach:

Permanent Delete:
Example
import os
def permanent_delete_file(file_path):
try:
# Check if the file exists
if os.path.exists(file_path):
# Remove the file permanently
os.remove(file_path)
print(f"{file_path} has been permanently deleted.")
else:
print(f"{file_path} does not exist.")
except Exception as e:
print(f"Error occurred while permanently deleting {file_path}: {e}")
# Example usage
permanent_delete_file("example.txt")
Safe Delete (Move to Recycle Bin):
Example
import send2trash
def safe_delete_file(file_path):
try:
# Check if the file exists
if os.path.exists(file_path):
# Move the file to the recycle bin
send2trash.send2trash(file_path)
print(f"{file_path} has been moved to the recycle bin.")
else:
print(f"{file_path} does not exist.")
except Exception as e:
print(f"Error occurred while moving {file_path} to the recycle bin: {e}")
# Example usage
safe_delete_file("example.txt")

5. Explain in detail (i)Assertions (ii)Logging (iii)Buttons in Debugging (iv)raising exceptions with code snippets wherever
necessary
A: (i) Assertions:
• Assertions are statements in Python used to ensure that a certain condition is true. If the condition evaluates to
`True`, the program continues execution as normal. However, if the condition evaluates to `False`, an
`AssertionError` exception is raised, halting the program's execution. Assertions are primarily used for
debugging and to check for logical errors in the code during development.
Example:
x = 10
# Assertion to ensure that x is positive
assert x > 0, "x should be positive"
print("x is positive")
In this example, if `x` is not positive, the assertion `x > 0` will fail, and an `AssertionError` will be raised with the message
`"x should be positive"`. This helps identify issues in the code during development.
(i) Logging:
• Logging is a mechanism used to record events, messages, and errors that occur during the execution of a
program. It provides a detailed record of the program's behavior, which can be useful for debugging,
monitoring, and troubleshooting. Python's `logging` module provides a flexible and powerful logging
framework.

Example:
import logging
# Configure logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
logging.error("Division by zero")
else:
logging.info(f"Division result: {result}")
return result
# Example usage
divide(10, 2)
divide(10, 0)
In this example, we configure the logging level to `DEBUG`, which means all messages will be logged. We define a `divide`
function that computes the division of two numbers. We use logging to record information messages (`INFO`) and error
messages (`ERROR`) during the execution of the function.
(ii) Buttons in Debugging:
• Buttons in debugging refer to the options available in a debugging environment to control the execution of a
program. Common debugging buttons include "Run", "Pause", "Step Over", "Step Into", and "Step Out". These
buttons allow developers to run the program, pause execution, step through code line by line, and navigate
through function calls.
• Debugging environments such as PyCharm, Visual Studio Code, and IDLE provide graphical buttons for these
debugging actions, making it easier for developers to interactively debug their code.

(iii) Raising Exceptions:


• In Python, exceptions can be raised manually using the `raise` statement. This is useful for signaling error
conditions or exceptional situations in the code. When an exception is raised, the program halts execution and
looks for an exception handler to handle the raised exception.
Example:
def sqrt(x):
if x < 0:
raise ValueError("Cannot compute square root of negative number")
return x ** 0.5

# Example usage
try:
result = sqrt(-10)
except ValueError as e:
print(e)
In this example, the `sqrt` function raises a `ValueError` exception if the input `x` is negative. When calling `sqrt(-10)`, the
exception is raised, and the error message "Cannot compute square root of negative number" is printed.
6. Explain how assertions can be used in traffic light simulation with Python code snippets.
A: Assertions can be used in a traffic light simulation to enforce certain conditions and behaviors of the traffic light
system. Here's how assertions could be integrated into a Python-based traffic light simulation:
1. Define Traffic Light States:
• First, define the different states of the traffic light, such as "Red", "Yellow", and "Green".
2. Assertion for Valid State Transition:
• Use assertions to ensure that the traffic light transitions between states correctly. For example, assert that the
traffic light can only transition from "Red" to "Green" and vice versa.

3. Simulation Loop:
• Implement a simulation loop where the traffic light changes its state based on predefined intervals or external
triggers.
Here's a basic example demonstrating how assertions can be used in a traffic light simulation:
class TrafficLight:
def __init__(self):
self.state = "Red"
def change_state(self, new_state):
# Assert that the new state is valid based on current state
assert (self.state == "Red" and new_state == "Green") or \
(self.state == "Green" and new_state == "Red"), \
"Invalid state transition"
self.state = new_state
# Example usage
traffic_light = TrafficLight()
# Initial state
print("Initial State:", traffic_light.state)
# Valid state transition
traffic_light.change_state("Green")
print("New State:", traffic_light.state)
# Invalid state transition (will raise AssertionError)
traffic_light.change_state("Red") # Shouldn't be possible to transition from Green to Red
In this example, we create a `TrafficLight` class with a `change_state` method to transition the traffic light between states.
We use assertions to enforce that the state transitions are valid. If an invalid state transition is attempted, an
`AssertionError` will be raised, indicating an issue with the simulation logic.

7. Explain the support for Logging with logging module in Python


A: The `logging` module in Python provides a flexible and powerful framework for logging messages, errors, and other
information during the execution of a program. It allows developers to record events and messages of varying severity
levels, making it easier to monitor and debug applications.
Key Features of the `logging` Module:

1. Logging Levels:

• The `logging` module supports different logging levels to categorize messages based on their severity. These levels
include `DEBUG`, `INFO`, `WARNING`, `ERROR`, and `CRITICAL`, in increasing order of severity.
2. Loggers:
• Loggers are objects used to create and manage log records. They provide a way to group related log messages
together. Multiple loggers can be created in a Python program, each with its own configuration.

3. Handlers:
• Handlers are responsible for determining what to do with the log records produced by loggers. They control
where the log messages are output, such as to the console, a file, or a network socket. Python provides various
built-in handlers like `StreamHandler`, `FileHandler`, `RotatingFileHandler`, `TimedRotatingFileHandler`, etc.

4. Formatters:
• Formatters specify the layout and format of log messages. They determine how log records are formatted before
being output by the handlers. Python's `logging` module supports customizable formatting options.
Example Usage:
import logging
# Configure logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s')
# Create a logger
logger = logging.getLogger("example_logger")
# Create a file handler and set the formatter
file_handler = logging.FileHandler("example.log")
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
file_handler.setFormatter(formatter)
# Add the file handler to the logger
logger.addHandler(file_handler)
# Log messages
logger.debug("This is a debug message")
logger.info("This is an info message")
logger.warning("This is a warning message")
logger.error("This is an error message")
logger.critical("This is a critical message")
In this example:
• We configure logging to set the logging level to `DEBUG` and define a basic logging format.
• We create a logger named "example_logger".
• We create a `FileHandler` to output log messages to a file named "example.log" and set a custom formatter.
• We add the file handler to the logger.
• We log messages at different levels using the logger (`logger.debug`, `logger.info`, `logger.warning`, `logger.error`,
`logger.critical`).

You might also like