MODULE 4
Organising Files
Debuggng
THE SHUTIL MODULE
The shutil (or shell utilities) module has functions to let copy, move, rename, and delete
files in Python programs.
Copying Files and Folders
The shutil module provides functions for copying files, as well as entire
folders.
Calling [Link](source, destination) will copy the file at the path source to
the folder at the path destination.
● [Link]() will copy a single file, [Link]() will copy an entire folder
and every folder and file contained in it.
● Calling [Link](source, destination) will copy the folder at the path
source, along with all of its files and subfolders, to the folder at the path
destination.
●
● The source and destination parameters are both strings. The function returns a
string of the path of the copied folder.
# importing shutil module
import shutil
source = "D:\PYTHON_PRGS\[Link]"
destination ="D:\Shutil_Code"
# Copy the content of source to destination
dest = [Link](source, destination)
# Print path of newly created file
print("Destination path:", dest)
Moving and Renaming Files and Folders
● Calling [Link](source, destination) will move the file or folder at the path
source to the path destination and will return a string of the absolute path of the
new location.
● If destination points to a folder, the source file gets moved into destination and
keeps its current filename.
>>import shutil
Assuming a folder named eggs already exists
>>[Link]('C:\\[Link]', 'C:\\eggs') in the C:\ directory, this [Link]() call says,
'C:\\eggs\\[Link]' “Move C:\[Link] into the folder C:\eggs.”
If there had been a [Link] file already in
C:\eggs, it would have been overwritten.
Since it’s easy to accidentally overwrite files
in this way, we should take some care when
using move().
>>[Link]('C:\\[Link]', the source file is moved and renamed.
'C:\\eggs\\new_bacon.txt')
'C:\\eggs\\new_bacon.txt'
Both of the previous examples worked under the assumption that there was a folder
eggs in the C:\ directory. But if there is no eggs folder, then move() will rename
[Link] to a file named eggs.
>>[Link]('C:\\[Link]', 'C:\\eggs') Here, move() can’t find a folder named
eggs in the C:\ directory and so assumes
that destination must be specifying a
'C:\\eggs'
filename, not a folder. So the [Link]
text file is renamed to eggs
[Link](source,destination) Copy the single file at the path If destination is a Returns a string or Path object of the copied
source to the folder at the path filename, it will be used file.
destination. as the new name of the 1 > [Link](p / '[Link]', p / 'some_folder')
copied file 'C:\\Users\\Al\\some_folder\\[Link]'
2 > [Link](p / '[Link]', p /
'some_folder/[Link]')
WindowsPath('C:/Users/Al/some_folder/[Link]')
[Link](source, copy the folder at the path The source and Returns a string of the path of the copied
destination) source, along with all of its destination parameters folder.
files and subfolders, to the are both strings >>> [Link](p / 'spam', p / 'spam_backup')
folder at the path destination. WindowsPath('C:/Users/Al/spam_backup')
[Link](source, Move the file or folder at the If the destination path Return a string of the absolute path of the new
destination) path source to the path specify a filename,The location.
destination source file is moved and [Link]('C:\\[Link]', 'C:\\eggs')
renamed. 'C:\\eggs\\[Link]'
[Link](path) Delete the file at path
[Link](path) Delete the folder at path
[Link](path) Remove the folder at path, and
all files and folders it contains
will also be deleted.
send2trash Safe Deletes with the send2trash is much safer send2trash.send2trash('ba
send2trash Module than Python’s regular delete [Link]')
functions, because it will
send folders and files to
computer’s trash or recycle
bin instead of permanently
deleting them.
[Link]() [Link]() function will [Link]() in a for loop for folderName,
return three values on each statement to walk a directory subfolders, filenames in
iteration through the loop: tree, much like use of the [Link]('C:\\delicious'):
range() function to walk over
A string of the current folder’s
a range of numbers
name
A list of strings of the folders in
the current folder
A list of strings of the files in the
current folder
Permanently Deleting Files and Folders
● Calling [Link](path) will delete the file at path.
● Calling [Link](path) will delete the folder at path. This folder must be
empty of any files or folders.
● Calling [Link](path) will remove the folder at path, and all files and
folders it contains will also be deleted.
Safe Deletes with the send2trash Module
Since Python’s built-in [Link]() 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.
WALKING A DIRECTORY TREE: Rename every file in some folder and also every file in every
subfolder of that folder.
● The [Link]() function is passed a single string value: the path of a folder.
● For Loop Statement
[Link]() function will return three values on each iteration through the loop:
● A string of the current folder’s name
● A list of strings of the folders in the current folder
● A list of strings of the files in the current folder
COMPRESSING FILES WITH THE ZIPFILE MODULE
● ZIP files (with the .zip file extension), which can hold the compressed contents
of many other files.
● Compressing a file reduces its size, which is useful when transferring it over
the internet.
● 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.
● zipfile is the name of the Python
module
● ZipFile() is the name of the
function.
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.
PROJECT: RENAMING FILES WITH AMERICAN-STYLE DATES TO EUROPEAN-STYLE DATES
Refer Text Book for programming example
Debugging: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
Program of Box_Print(Refer Text book)
def boxPrint(symbol, width, height): print(symbol * width)
if len(symbol) != 1: for i in range(height - 2):
raise Exception('Symbol must be a print(symbol + (' ' * (width - 2)) + symbol)
single character string.')
print(symbol * width)
if width <= 2:
for sym, w, h in (('*', 4, 4), ('O', 20, 5), ('x', 1, 3), ('ZZ',
raise Exception('Width must be 3, 3)):
greater than 2.')
try:
if height <= 2:
boxPrint(sym, w, h)
raise Exception('Height must be
greater than 2.') except Exception as err:
print('An exception happened: ' + str(err))
GETTING THE TRACEBACK AS A STRING : When Python encounters an error, it produces a
treasure trove of error information called the traceback. The traceback includes the error
message, the line number of the line that caused the error, and the sequence of the function
calls that led to the error. This sequence of calls is called the call stack.
1 def spam(): Traceback (most recent call last):
2 bacon() File "[Link]", line 7, in <module>
spam()
3
File "[Link]", line 2, in spam
4 def bacon():
bacon()
5 raise Exception('This is the error message.') File "[Link]", line 5, in bacon
6 raise Exception('This is the error
message.')
7 spam() Exception: This is the error message.
Assertions are statements that assert or state a fact confidently in program.
● Assertions are simply boolean expressions 1. Python has built-in ASSERT statement
that check if the conditions return true or to use assertion condition in the
not. program.
● If it is true, the program does nothing and
2. statement has a condition or expression
moves to the next line of code.
● However, if it's false, the program stops which is supposed to be always true.
and throws an error. 3. If the condition is false assert halts the
In code, an assert statement consists of the following:
program and gives an Assertion Error
● The assert keyword
● A condition (that is, an expression that evaluates
to True or False)
● A comma
● A string to display when the condition is False
def avg(marks):
OUTPUT:
assert len(marks) != 0,"List is empty."
return sum(marks)/len(marks)
Average of mark2: 78.0
AssertionError: List is empty
mark2 = [55,88,78,90,79]
print("Average of mark2:",avg(mark2))
mark1 = []
print("Average of mark1:",avg(mark1))
LOGGING
● Logging is a great way to understand what’s happening in program and in
what order it’s happening.
● Python’s logging module makes it easy to create a record of custom
messages that we write.
● These log messages will describe when the program execution has reached
the logging function call and list any variable specified at that point in time.
To enable the logging module to display log messages
import logging
[Link](level=[Link], format=' %(asctime)s - %(levelname)
s - %(message)s')
Python logging is a module that allows to track events that occur while your
program is running.
logging record information about errors, warnings, and other events that occur
during program execution.
And logging is a useful tool for debugging, troubleshooting, and monitoring
program.
import logging
[Link](level=[Link], format='%(asctime)s - %(levelname)s
- %(message)s')
[Link]('Start of program')
def factorial(n):
[Link]('Start of factorial(%s%%)' % (n))
total = 1
for i in range(n + 1):
total *= i
[Link]('i is ' + str(i) + ', total is ' + str(total))
[Link]('End of factorial(%s%%)' % (n))
return total
print(factorial(5))
[Link]('End of program')
Logging Levels
Logging levels provide a way to categorize your log messages by importance.
Level Logging function Description
DEBUG[10] [Link]() The lowest level. Used for
small details.
INFO[20] [Link]() Used to record information on
general events in your program
WARNING[30] [Link]() Used to indicate a potential
problem that doesn’t prevent
the program from working but
might do so in the future.
ERROR [Link]() Used to record error that causes program fail to do
something
CRITICAL [Link]() The HIGHEST LEVEL.
Fatal Error
Disabling Logging
● The [Link]() function disables these so that we don’t have to go into program and
remove all the logging calls by hand.
● pass [Link]() a logging level, and it will suppress all log messages at that level or lower.
import logging
>>> [Link](level=[Link], format=' %(asctime)s -
%(levelname)s - %(message)s')
>>> [Link]('Critical error! Critical error!')
2019-05-22 11:10:48,054 - CRITICAL - Critical error! Critical error!
>>> [Link]([Link])
>>> [Link]('Critical error! Critical error!')
>>> [Link]('Error! Error!')
Logging to a File
Instead of displaying the log messages to the screen, write them to a text file.
The [Link]() function takes a filename keyword argument, like so:
import logging
[Link](filename='[Link]', level=[Link], format='
%(asctime)s - %(levelname)s - %(message)s')
While logging messages are helpful, they can clutter your screen and make it hard to
read the program’s output. Writing the logging messages to a file will keep your screen
clear and store the messages so you can read them after running the program.
IDLE’s Debugger
● The debugger will run a single line of code and then wait for you to tell it to continue.
● To run a program under Mu’s debugger, click the Debug button in the top row of buttons, next to
the Run button.
● Debugging mode also adds the following new buttons to the top of the editor: Continue, Step
Over, Step In, and Step Out. The usual Stop button is also available.
Go: Clicking the Go button will cause the program to execute normally until it terminates or reaches a
breakpoint.
Step: Clicking the Step button will cause the debugger to execute the next line of code and then pause
again
Over: Clicking the Over button will execute the next line of code, similar to the Step button. However, if
the next line of code is a function call, the Over button will “step over” the code in the function. The
function’s code will be executed at full speed.
Out: Clicking the Out button will cause the debugger to execute lines of code at full speed until it returns
from the current function.
Quit: If you want to stop debugging entirely and not bother to continue executing the rest of the program,
click the Quit Button.
For example, if the next line of code calls a spam() function but you don’t really care about code inside this
function, you can click Step Over to execute the code in the function at normal speed, and then pause when
the function returns.
Step Out
Clicking the Step Out button will cause the debugger to execute lines of code at full speed until it returns
from the current function. If you have stepped into a function call with the Step In button and now simply
want to keep executing instructions until you get back out, click the Out button to “step out” of the current
function call.
Stop
If you want to stop debugging entirely and not bother to continue executing the rest of the program, click the
Stop button. The Stop button will immediately terminate the program.