Python 4
Python 4
OS Module
05
The OS module in Python provides functions for interacting with the operating system. o
comes under Python's standard utility modules. This module provides a portable way
modules include
using operating system-dependent functionality. The *os and os.path
many functions to interact with the file system.
getcwd(0
mkdir()
makedirs()
remove()
rmdir()
shutil Module
Shutil module offers high-level operation on a file like a copy, create, and remote operation
on the file. It comes under Python's standard utility modules. This module helps in
automating the process of copying and removal of files and directories.
import shutil, os
os.chdir('sample_data')
shutil.copy('/content/sample_data/mnist_test.csv', '/content/delicious/")
shutil.copytree('/content/sample_data','/content/fold')
shutil.move('/content/sample_data/delicious, "/content/delicious")
for filename in os.listdir():
if filename.endswith(".txt'):
os.unlink(filename)
os.unlink(path)
os.rmdir(path)
shutil.rmtree(path)
import send2trash
baconFile.close ()
send2trash.send2trash('bacon.txt')
OS.walk) generate the file names in a directory tree by walking the tree either top-down or
bottom-up. For each directory in the tree rooted at directory top (including top itself), it
yields a 3-tuple (dirpath, dirnames, filenames).
os.walk('CA\delicious')
You may be familiar with 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. And
since a ZIP fle 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.
import zipfile
exampleZip = zipfile.ZipFile('new.zip')
exampleZip.namelist()
filelnfo = exampleZip.getinfo('mnist_test.csv')
filelnfo.file size
fileinfo.compress_size
exampleZip.close()
exampleZip.extractall()
exampleZip.close()
execute invalid code. (try & except)
Python raises an exception whenever it tries to
a raise statement consists of the
EXceptons are raised with a raise statement In code.
following:
" The raise keyword
"A call to the Exception()) function
Exception() function
"A string with a helpful error mnessage passed to the
kk* *
*** *
O0000000000000000000
0000000000000000000o
O0000000000000000000
O00000000000O0000000
XXX
X X
XXX
When Python encounters an error, it produces a treasure trove of error
message,
information called the traceback. The traceback includes the error
of the line that caused the error, and the sequence of the
the line number
function calls that led to the error. This sequence of calls is called the call stack.
import traceback
try:
raise Exception('This is the error message.")
except:
errorFile = open('errorlnfo.txt', 'w')
errorFile.write(traceback.format_exc())
errorFile.close()
print('The traceback info was written to errorlnfo.txt.)
An assertion is a sanity check to make sure your code isn't doing something
obviously wrong. These sanity checks are performed by assert statements. If
the sanity check fails, then an AssertionError exception is raised.
podBayDoorStatus ='open'
assert podBayDoorStatus == 'open', 'The pod bay doors need to be "open".
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 iin 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')
logging.basicConfig(level=logging. DEBUG,format%(asctime)s -
%(levelname)s - %(message)s')
>>> logging.debug('Some debugging details.")
2015-05-18 19:04:26,901 - DEBUG - Some debugging details.
» logging.info('The logging module is working.')
2015-05-18 19:04:35,569 - INFO -The logging module is working.
to be logged.")
>>> logging.warning('An error message is about message is about to be logged.
2015-05-18 19:04:56,843 - WARNING - An error
>>> logging.error('An error has occurred.')
2015-05-18 19:05:07,737 - ERROR - An error has occurred.
>>> logging.critical('The program is unable to recover!")
to recover!
2015-05-18 19:05:45,794 - CRITICAL - The program is unable