Traceback As A String, Assertions, Logging, IDLE S Debugger
Traceback As A String, Assertions, Logging, IDLE S Debugger
Traceback As A String, Assertions, Logging, IDLE S Debugger
import shutil
shutil.copy('C:\\Users\\girishns\\Desktop\\src\\abc.txt',
'C:\\Users\\girishns\\Desktop\\dest\\ds.txt')
Shutil.copy(‘C:\\src\\file1.txt’, ’C:\\dest\\file2.txt’)
Copying Files and Folders
>>>shutil.copy('C:\\spam.txt', 'C:\\folder1’)
'C:\\folder1\\spam.txt‘
'C:\\folder1\\eggs2.txt'
shutil.copy() will copy a single file.
'C:\\ folder2_backup'
Moving and Renaming Files and Folders
'C:\\eggs\\file1.txt'
shutil.move('C:\\abc.txt‘ , 'C:\\fldr\\new_abc.txt')
'C:\\fldr\\new_abc.txt'
Permanently Deleting Files and Folders
import send2trash
send2trash.send2trash(‘abc.txt')
Walking a Directory Tree
If we want to rename every file in some folder
and also every file in every subfolder of that
folder.
http:// nostarch.com/automatestuff/
Compressing Files with the zipfile Module
ZIP files (with the .zip file extension), which can hold the
compressed contents of many other files.
Python program can both create and open (or extract) ZIP files
using functions in the zipfile module
Reading ZIP Files
f.txt
>>>example.namelist()
['xyz/a/', 'xyz/a/f.txt', 'xyz/bb/', 'xyz/cd.txt']
fileino = example.getinfo(‘f.txt')
ZipInfo objects have
>>> fileinfo.file_size their own attributes, such
as file_size and
13908 compress_size in bytes,
which hold integers of the
>>> fileinfo.compress_size original file size and
3828 compressed file size,
respectively.
Extracting from ZIP Files
>>> file.close()
file = zipfile.ZipFile('new.zip', 'w')
Parameters
file: This argument should be a filename or the path
to a zip file.
left ……………….!
Project: Backing Up a Folder into a ZIP File
Step 1: Figure Out the ZIP File’s Name The code for this
program will be placed into a function named backupToZip().
Step 3: Walk the Directory Tree and Add to the ZIP File.
import zipfile, os
def backupToZip(folder):
folder = os.path.abspath(folder) # make sure folder is absolute
number = 1
while True:
zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'
if not os.path.exists(zipFilename):
break
number = number + 1
print('Creating %s...' % (zipFilename))
backupZip = zipfile.ZipFile(zipFilename, 'w')
for foldername, subfolders, filenames in os.walk(folder):
print('Adding files in %s...' % (foldername))
backupZip.write(foldername)
for filename in filenames:
if filename.startswith(os.path.basename(folder) + '_') and filename.endswith('.zip'):
continue
backupZip.write(os.path.join(foldername, filename))
backupZip.close()
print('Done.')
backupToZip('C:\\delicious')
Debugging:
Raising Exceptions,
Getting the Traceback as a String,
Assertions,
Logging,
IDLE’s Debugger (Integrated Development and
Learning Environment ).
A debugger is a program that can
help you find out what is going on in
a computer program
The Best Tools to Debug Python
Sentry. Sentry is an error-tracking and performance-
monitoring tool that can diagnose and resolve python
problems. ...
Pycharm. Pycharm is a python-focused IDE featuring
some of the greatest python debugging tools available.
Rollbar. ...
Instabug. ...
Visual Studio. ...
Raygun. ...
Glitchtip. ...
Komodo IDE.
Raising Exceptions
print(symbol * width)
for i in range(height - 2):
print(symbol + (' ' * (width - 2)) + symbol)
print(symbol * width)
for sym, w, h in (('*', 4, 4), ('O', 20, 5), ('x', 1, 3), ('ZZ', 3, 3)):
try:
boxPrint(sym, w, h)
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.
def spam():
bacon()
def bacon():
raise Exception('This is the error message.')
spam()
116
The traceback info was written to errorInfo.txt
Assertions
It is a debugging tool, and its primary task is to check
the condition. If it finds that the condition is true, it
moves to the next line of code, and If not, then stops
all its operations and throws an error.
import logging
logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')
import logging
logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s - %(message)s')
logging.debug('Start of program')
num=5
sum = 0
while(num > 0):
sum = sum+num
logging.debug('num is ' + str(num) + ', total is ' + str(sum))
num = num-1
print("The sum is", sum)
logging.debug('End of program')
>>> logging.disable(logging.CRITICAL)
Logging to a File
logging.basicConfig(filename='myLog.txt', level=logging.DEBUG,
format=' %(asctime)s - %(levelname)s - %(message)s')
IDLE’s Debugger