0% found this document useful (0 votes)
28 views11 pages

Python QB Solns (Mod 4)

Uploaded by

adi28gowda
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)
28 views11 pages

Python QB Solns (Mod 4)

Uploaded by

adi28gowda
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/ 11

PYTHON MODULE -4

1.
i) copying files and folders
we can copy files and folders by using shutil.copy() method. this method is used to copy the
content of the source file to destination file or directory. the meta data of the file is not
copied in this method.
Syntax: shutil.copy(source, destination, )
where,
source: is the string representing the path of the source file.
destination: A string representing the path of the destination file or directory.

ii) moving files and folders


we can move files and folders using shutil.move() method. this method recursively moves a
file or directory (source) to another location (destination) and returns the destination. If the
destination directory already exists then source content is moved inside that directory. If
the destination already exists but is not a directory then it may be overwritten depending
on os.rename() semantics.
Syntax: shutil.move(source, destination)
where,
source: A string representing the path of the source file.
destination: A string representing the path of the destination directory.
iii) permanently deleting files and folders.
we can permanently delete files and folders using the os.remove() method for files and
os.rmdir() method for directories.
Syntax: os.remove(path) and os.rmdir(path)
where,
path: A path-like object representing a file path. A path-like object is either a string or bytes
object representing a path.
2.
shutil.copy() method is used to copy the content of the source file to destination file or
directory. the meta data of the file is not copied in this method.
whereas
shutil.copytree() method is used to copy an entire directory tree rooted at source(src) to the
destination directory(drc). The destination directory must not already exist. It will be
created during copying.
Syntax: shutil.copy(source, destination, )
where,
source: is the string representing the path of the source file.
destination: A string representing the path of the destination file or directory.
Syntax: shutil.copytree(src, dst, symlinks = False, ignore = None, copy_function = copy2,
igonre_dangling_symlinks = False)
Parameters:
src: A string representing the path of the source directory.
dest: A string representing the path of the destination.
3 question is having same answers as the above
shutil.copy2() method in Python is used to copy the content of source file to destination file
or directory. This method is identical to shutil.copy() method but it also tries to preserves
the file’s metadata.
Syntax: shutil.copy2(source, destination)
source: A string representing the path of the source file.
destination: A string representing the path of the destination file or directory.

4. explain safe delete. (Other part is permanent delete which is the same.)
Using send2trash, we can send files to the Trash or Recycle Bin instead of permanently
deleting them.
Modules required
OS : The OS module in Python provides functions for interacting with the operating
system. OS module comes with Python’s Standard Library.
send2trash : Send2Trash is a small package that sends files to the Trash (or Recycle Bin)
natively and on all platforms. To install it type the below command in the terminal.
pip install send2trash
import os
import send2trash
for folder, subfolders, files in os.walk('/Users/tithighosh/Documents'):
for file in files:
if file.endswith('.txt'):
path = os.path.join(folder, file)
print('deleted : ', path )
send2trash.send2trash(path)
output:

5. answer given above.

6.
output

the file path

7.
Benefits of compressing files:
1. *Reduced storage space*: Compressing files reduces their size, allowing more data to be
stored in the same amount of space.
2. *Faster file transfer*: Smaller files transfer more quickly over networks or when sending
via email.
3. *Lower bandwidth usage*: Compressed files require less bandwidth when transferring
over the internet, making them faster and cheaper to transmit.
4. *Consolidation*: Multiple files can be compressed into a single archive, making it easier
to manage and share them as a group.
5. *Organization*: Compressed files can help organize related files together, reducing
clutter and simplifying file management.
6. *Security*: Encrypted compression formats can provide an additional layer of security for
sensitive data.
8.

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,"doesnt 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 creating zip archive")

9.
a zipfile is a type of file that contains compressed content of many other files which are
compressed hence, the file size is reduced making it easier to transfer it over the internet.
a single file is known as archive file.
# to create and add to a zip file
>>> import zipfile
>>>new_zip=zipfile.ZipFile(‘new.zip’,’w’)
>>>newZip.write(‘spam.txt’,compress_type=zipfile.ZIP_DEFLATED)
>>>newZip.close()
10. same answer as 8th one
11. illustrate os.walk() function with suitable example
The os.walk() method generates the file and directory names in a directory tree by walking
the tree using top-down or bottom-up approach.
Each directory in the tree is rooted to the top directory. It yields a tuple that contains
directory path, directories name and file name
syntax: os.walk(top)
where,
top represents path like object to be traversed.

12.define assertions . explain with suitable example


assertion is the Boolean expression that checks if the statement is True or False. If the
statement is true then it does nothing and continues the execution, but if the statement is
False then it stops the execution of the program and throws an error.
Syntax : assert condition
condition : The boolean condition returning true or false.
it Returns Assertion Error, in case the condition evaluates to false along with the error
message which when provided.
example:
# initializing number
a=4
b=0
# using assert to check for 0
print("The value of a / b is : ")
assert b != 0
print(a / b)

13. raising exceptions in python:


The raise keyword is used to raise an exception. You can define what kind of error to raise,
and the text to print to the user.

14. logging and logging module


logging is a means of tracking events that happen when some software runs it is important
for software developing debugging and running as we can track down the errors easily
when a program or software crashes.
there are 5 built levels of logging:
DEBUG: the lowest level, it is used for small details usually you care about messages only
when diagnosing problems. (logging.debug())
INFO: used to record info on general events in your program or confirm that things are
working at their point of execution. (logging.info())
WARNING: used to indicate a potential problem that doesn’t prevent the program from
working but might do so in future. (logging.warning())
ERROR: used to record an error that caused the program to fail to do
something(logging.error())
CRITICAL: it is the highest level used to indicate a fatal error that has caused or about to
cause the program to stop running entirely. (logging.critical())

15.

output

code

16. same as question 13.


*****************end of module 4*******************

You might also like