Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

3 Programming-In-python Key Notes j Rexy

File

Uploaded by

aryan220535
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

3 Programming-In-python Key Notes j Rexy

File

Uploaded by

aryan220535
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

EXCEPTION HANDLING IN PYTHON

• Errors are the problems in a program due to which the program will stop
the execution.

Two types of Error occurs in python.

• Syntax errors(parsing errors)

• Logical errors (Exceptions)

• An exception is an event, which occurs during the execution of a program


that disrupts the normal flow of the program's instructions. In general,
when a Python script encounters a situation that it cannot cope with, it
raises an exception. An exception is a Python object that represents an
error.

Page 1 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
Page 2 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
COMMON EXCEPTIONS:
• ZeroDivisionError: Occurs when a number is divided by zero.

• NameError: It occurs when a name is not found. It may be local or


global.

• IndentationError: If incorrect indentation is given.

• IOError: It occurs when Input Output operation fails.

• EOFError: It occurs when the end of the file is reached, and yet
operations are being performed.

Page 3 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
Page 4 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
EXAMPLE:

Page 5 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
RAISE AN EXCEPTION:

• As a Python developer you can choose to throw an exception if a


condition occurs.

• To throw (or raise) an exception, use the raise keyword.

• We can use raise to throw an exception if a condition occurs. The


statement can be complemented with a custom exception.

• x = -1

if x < 0:
raise Exception("Sorry, no numbers below zero")

• x = "hello"

if not type(x) is int:


raise TypeError("Only integers are allowed")

# Program to depict else clause with try-except


# Function which returns a/b

Page 6 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
def AbyB(a , b):
try:
c = ((a+b) / (a-b))
except ZeroDivisionError:
print "a/b result is 0"
else:
print c
# Driver program to test above function
AbyB(2.0, 3.0)
AbyB(3.0, 3.0)

OUTPUT:

-5.0

a/b result is 0

USER DEFINED EXCEPTION


• Programmers may name their own exceptions by creating a new exception
class. Exceptions need to be derived from the Exception class, either
directly or indirectly.

Page 7 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
ASSERTION IN PYTHON

• An Assertion in Python or a Python Assert Statement is one which asserts


(or tests the trueness of) a condition in your code. This is a Boolean
expression that confirms the Boolean output of a condition.

Where Assertion in Python used?

• In checking types/ in checking valid input.

• In checking values of arguments.

• Checking outputs of functions.

• As a debugger to halt where an error occurs.

• In testing code.

• In detecting abuse of an interface by another programmer.

Using assert without Error Message:

def avg(marks):

assert len(marks) != 0

return sum(marks)/len(marks)

mark1 = []

print("Average of mark1:",avg(mark1))

Page 8 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
Using assert with Error Message

LOGGING AN EXCEPTION

• Logging, in software applications, is a way to track events. Before we can


proceed, telling you more about it, we want to exemplify.

• To log an exception in Python we can use logging module and through


that we can log the error.

• Logging an exception in python with an error can be done in the logging.


exception() method. This function logs a message with level ERROR on
this logger. The arguments are interpreted as for debug(). Exception info
is added to the logging message. This method should only be called from
an exception handler

PURPOSES OF LOGGING IN PYTHON

• Diagnostic Logging- To record events that revolve around the


application’s operation.

• Audit Logging- To record events for business analysis.

Page 9 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
• Logging module provides a set of functions for simple logging and for
following purposes

DEBUG

INFO

WARNING

ERROR

CRITICAL

PYTHON LOGGING FUNCTIONS

• logging.info() or logging.debug() for the detailed output of events that


occur during normal operation of a program.

• warnings.warn() issues a warning for a runtime event if the issue is


avoidable.

• logging.warning() issues a warning for a runtime event if we need to note


the event even when the client can do nothing about it.

• logging.error(), logging.exception(), or logging.critical() report the


suppression of an error without raising an exception.

# importing the module


import logging
try:
printf(“Hello")
except Exception as Argument:
logging.exception("Error occured while printing Hello")
ERROR:root:Error occured while printing GeeksforGeeks Traceback (most
recent call last): File "/home/gfg.py", line 3, in printf("GeeksforGeeks")
NameError: name 'printf' is not defined
We can also log the error message into different file without showing error
in the console by the following method:

Page 10 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
Logging Variable Data:
dynamic information from application in the logs.
import logging
name = 'John‘
logging.error('%s raised an error', name)
ERROR:root:John raised an error
Displaying Date/Time For Python Logging:
• logging.basicConfig(format=’%(asctime)s %(message)s’)

FILE IN PYTHON
• A file is a chunk of logically related data or information
which can be used by computer programs.
• Files on most modern file systems are composed of three
main parts:
• Header: metadata about the contents of the file (file name,
size, type, and so on)
• Data: contents of the file as written by the creator or editor

Page 11 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
• End of file (EOF): special character that indicates the end
of the file
In Python, there is no need for importing external library to read
and write files. Python provides an inbuilt function for creating,
writing, and reading files.
• Python has several functions for creating, reading,
updating, and deleting files.
• There are two types of files in Python
Binary file
Text file

Page 12 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
FILE open() function
The Python file open function returns a file object that contains methods and
attributes to perform various operations for opening files in Python.

file_object = open("filename", "mode")


Here,

filename: gives name of the file that the file object has opened.
mode: attribute of a file object tells you which mode a file was opened in.
Page 13 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
File Modes:

MODES DESCRIPTION

It opens a file in read-only mode while the file offset


<r>
stays at the root.

It opens a file in (binary + read-only) modes. And the


<rb>
offset remains at the root level.

It opens the file in both (read + write) modes while the


<r+>
file offset is again at the root level.

It opens the file in (read + write + binary) modes. The


<rb+>
file offset is again at the root level.

It allows write-level access to a file. If the file already


<w> exists, then it’ll get overwritten. It’ll create a new file if
the same doesn’t exist.

Use it to open a file for writing in binary format. Same


<wb>
behavior as for write-only mode.

It opens a file in both (read + write) modes. Same


<w+>
behavior as for write-only mode.

It opens a file in (read + write + binary) modes. Same


<wb+>
behavior as for write-only mode.

Page 14 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
It opens the file in append mode. The offset goes to the
<a> end of the file. If the file doesn’t exist, then it gets
created.

It opens a file in (append + binary) modes. Same


<ab>
behavior as for append mode.

It opens a file in (append + read) modes. Same behavior


<a+>
as for append mode.

It opens a file in (append + read + binary) modes. Same


<ab+>
behavior as for append mode.

Syntax:

• file_object = open(file_name, mode)

EG

• f = open("demofile.txt", "r")

Page 15 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
EXAMPLE:

# Python program to demonstrate File Concept

file1 = open('IIBSC_CS.txt', 'w')

L = [“20UCS BATCH \n", "JAVA-PYTHON-DS \n", "VB-EVS \n"]

s = "WELCOME\n"

# Writing a string to file

file1.write(s)

# Writing multiple strings at a time

file1.writelines(L)

# Closing file

file1.close()

file1 = open('IIBSC_CS.txt', 'r')

print(file1.read())

file1.close()

Page 16 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
APPEND

# Python program to illustrate # Append

# Append-adds at last

file1 = open("IIBSC_CS.txt", "a") # append mode

file1.write("STAND-ECC-NSS-FINE ARTS \n")

file1.close()

file1 = open("IIBSC_CS.txt", "r")

print("Output after appending")

print(file1.read())

print()

file1.close()

Page 17 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
EXAMPLE:

Python program to count the number of lines in a text file

# Opening a file

file = open("IIBSC_CS.txt","r")

Counter = 0

# Reading from file

Content = file.read()

CoList = Content.split("\n")

for i in CoList:

if i:

Page 18 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
Counter += 1

print("Number of lines in the file IIBSC_CS.txt")

print(Counter)

EXAMPLE:

PROGRAM TO DISPLAY SUM OF DIGITS IN THE TEXT FILE

# Python program for writing to file

file = open('SUM.txt', 'w')

data ='HELLO123 SUPER345'

file.write(data)

file.close()

# Python program for reading from file

h = open('SUM.txt', 'r')

content = h.readlines()

a=0

for line in content:

for i in line:

if i.isdigit() == True:

a += int(i)

print("The sum of numbers in the file is:", a)

Page 19 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
EXAMPLE

Count the number of occurrence of the words in text file

file = open('COUNT.txt', 'w')

data ='IUG IIUG IIIUG IPG IIPG IIUG IIUG IIUG'

file.write(data)

file.close()

text = open("COUNT.txt", "r")

d = dict()

for line in text:

line = line.strip()

line = line.upper()

words = line.split(" ")

for word in words:

if word in d:

d[word] = d[word] + 1

else:

d[word] = 1

Page 20 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
for key in list(d.keys()):

print(key, ":", d[key])

FILE METHODS:

close() Closes the file

detach() Returns the separated raw stream from the buffer

fileno() Returns a number that represents the stream, from the


operating system's perspective

flush() Flushes the internal buffer

isatty() Returns whether the file stream is interactive or not

Page 21 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
read() Returns the file content

readable() Returns whether the file stream can be read or not

readline() Returns one line from the file

readlines() Returns a list of lines from the file

seek() Change the file position

seekable() Returns whether the file allows us to change the file


position

tell() Returns the current file position

truncate() Resizes the file to a specified size

writable() Returns whether the file can be written to or not

write() Writes the specified string to the file

writelines() Writes a list of strings to the file

Page 22 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
FILE:RANDOM ACCESS

FILE

The tell() method returns the current file position in a file stream.

file.tell()

f = open("demofile.txt", "r")
print(f.readline())
print(f.tell())

seek()

move the file pointer to another position. fileObject.seek(offset,from_what))

offset – A number of positions will move.

from_what – defines your point of reference. (Optional)

f = open("testFile.txt", "r")

f.seek(9)

print(f.readline())

Using the mmap module allows the user to randomly access locations in a file
by mapping the file into memory. This is an alternative to using normal file
operations.

import mmap

with open('filename.ext', 'r') as fd:


# 0: map the whole file
mm = mmap.mmap(fd.fileno(), 0)

# print characters at indices 5 through 10


print mm[5:10]
Page 23 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
# print the line starting from mm's current position
print mm.readline()

# write a character to the 5th index


mm[5] = 'a'

# return mm's position to the beginning of the file


mm.seek(0)

# close the mmap object


mm.close()

Zipping and Unzipping files in Python


ZIP is an archive file format that supports lossless data compression.
By lossless compression, it means that the
compression algorithm used allows the original data to be perfectly
reconstructed from the compressed data.
Also, a ZIP file may contain one or more files or directories that may
have been compressed.
Why do we need zip files?
To reduce storage requirements.
To improve transfer speed over standard connections.

# importing required modules


from zipfile import ZipFile

# specifying the zip file name


file_name = "my_python_files.zip"

# opening the zip file in READ mode


with ZipFile(file_name, 'r') as zip:
# printing all the contents of the zip file
zip.printdir()
Page 24 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY
# extracting all the files
print('Extracting all the files now...')
zip.extractall()
print('Done!')

Unzipping the File


import zipfile
def un_zipFiles(path):
files=os.listdir(path)
for file in files:
if file.endswith('.zip'):
filePath=path+'/'+file
zip_file = zipfile.ZipFile(filePath)
for names in zip_file.namelist():
zip_file.extract(names,path)
zip_file.close()

Page 25 of 25
PROGRAMMING IN PYTHON: MATERIAL: PROF J. REXY

You might also like