Unit-2 Python Programming
Unit-2 Python Programming
CO1 2 2 2 2
2
CO2 2 2
2
CO3 2 2 2
2 3 2
CO4 2 2 3 3 3
2
CO5 2 3 3
2/27/2023 4
Syllabus Content
Unit – III Exception Handling and Multi-Threading in python
6
Exception handling: try, except and finally block, handling multiple
exceptions, raise an exception, User defined exception- python
multithreading- thread and threading module-Synchronizing Threads in
Python.
Case Study: Development of student performance evaluation report
Text Books:
• Guido van Rossum, Learning Python: Crash Course Tutorial, The Python
development team publishers, 2020. [Unit-1,2,3]
• Bharti Motwani, Data Analytics using Python, paperback edition, Wiley
Publishing Ltd, 2020. [Unit-4]
• James R. Parker, Game Development Using Python, 2nd edition, Mercury
Learning and Information publishers,, 2021. [Unit-5]
2/27/2023 6
Syllabus Content
Reference Books:
• David M.Baezly , Python Essential Reference, 5th edition, Addison-
Wesley Professional;, 2021.
• John Shovic, Alan Simpson, Python for dummies. John Wiley & Sons,
2020.
Online References:
• Programming for Everybody (Getting Started with Python), Accessed on
02, April 2021 [Online] Available: https://www.coursera.org/learn/python
• Learn Python, Accessed on 02, April 2021 [Online] Available:
https://www.udemy.com/course/python-the-complete-python-developer-
course
• Introduction to Python Programming, Accessed on 02, April 2021 [Online]
Available: https://www.edx.org/professional-certificate/introduction-to-
python-programming
• The Python Standard Library, Accessed on 02, April 2021 [Online]
Available: https://docs.python.org/3/library
2/27/2023 7
Manipulating files & directories
Directories
All files are contained within various directories.
The os module has several methods that help you create, remove,
and change directories.
mkdir() – creates directories in current working directory.
chdir() – changes the current working directory.
rmdir() – deletes the directory. To ensure deletion all its contents should
be removed.
getcwd() – displays the current working directory.
Example code
• Binary file
• Text file
Binary files in Python
• All binary files follow a specific format. We can open some binary
files in the normal text editor but we can’t read the content present
inside the file. That’s because all the binary files will be encoded in
the binary format, which can be understood only by a computer or
machine.
• For handling such binary files we need a specific type of software to
open it.
• For Example, You need Microsoft word software to open .doc
binary files. Likewise, you need a pdf reader software to open .pdf
binary files and you need a photo editor software to read the image
files and so on.
Binary files in Python (cont…1)
• Most of the files that we see in our computer system are called
binary files.
• Example:
• Document files: .pdf, .doc, .xls etc.
• Image files: .png, .jpg, .gif, .bmp etc.
• Video files: .mp4, .3gp, .mkv, .avi etc.
• Audio files: .mp3, .wav, .mka, .aac etc.
• Database files: .mdb, .accde, .frm, .sqlite etc.
• Archive files: .zip, .rar, .iso, .7z etc.
• Executable files: .exe, .dll, .class etc.
Text files in Python
• A text file is usually considered as sequence of lines. Line is a
sequence of characters (ASCII), stored on permanent storage media.
Although default character coding in python is ASCII but supports
Unicode as well.
• in text file, each line is terminated by a special character, known as
End of Line (EOL). From strings we know that \n is newline
character.
• at the lowest level, text file is collection of bytes. Text files are stored
in human readable form.
• they can also be created using any text editor.
Text files in Python
• Text files don’t have any specific encoding and it can be opened in
normal text editor itself.
• Example:
• Web standards: html, XML, CSS, JSON etc.
• Source code: c, app, js, py, java etc.
• Documents: txt, tex, RTF etc.
• Tabular data: csv, tsv etc.
• Configuration: ini, cfg, reg etc.
Operations in Files
Named locations on disk to store related information.
They are used to permanently store data in a non-volatile memory.
When we want to read from or write to a file, we need to open it
first.
When we are done, it needs to be closed so that the resources that are
tied with the file are freed.
Hence, in Python, a file operation takes place in the following order:
- A.Opening a file.
- B.Reading or writing (perform operation).
- C.Closing the file.
What is Buffering ?
• Buffering is the process of storing a chunk of a file in a temporary
memory until the file loads completely. In python there are different
values can be given. If the buffering is set to 0
, then the buffering is off. The buffering will be set to 1 when we
need to buffer the file.
Opening Files in Python (cont…5)
• In order to read a file in python, we must open the file in read mode.
• There are three ways in which we can read the files in python.
– read([n])
– readline([n])
– readlines() – all lines returned to a list
• Here, n is the number of bytes to be read.
Reading Information in the File
Example 1:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.read(5))
Output:
Hello
•Here we are opening the file test.txt in a read-only mode and are
reading only the first 5 characters of the file using the
my_file.read(5) method.
Reading Information in the File
Example 2:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.read())
Output:
Hello World Hello
Python Good
Morning
Here we have not provided any argument inside the read()
function. Hence it will read all the content present inside the
file.
Reading Information in the File
Example 3:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.readline(2))
Output:
He
Example 4:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.readline())
Output:
Hello World
Example 5:
my_file = open(“C:/Documents/Python/test.txt”, “r”)
print(my_file.readlines())
Output:
*‘Hello World\n’, ‘Hello Python\n’, ‘Good Morning\n’, ‘How are
You’+
Here we are reading all the lines present inside the text file
including the newline characters.
Reading Information in the File
Reading a specific line from a File
line_number = 4
fo = open(“C:/Documents/Python/test.txt”, ’r’)
currentline = 1
for line in fo:
if(currentline == line_number): print(line)
break
currentline = currentline +1
Output:
How are You
In the above example, we are trying to read only the 4th line
from the ‘test.txt’ file using a “for loop”.
Reading Information in the File
Output: Hello
World Hello
Python
Good Morning
How are You
B.Writing a file
In order to write into a file in Python, we need to open it in write w,
append a or exclusive creation x mode.
Need to be careful with the w mode, as it will overwrite into the file
if it already exists. Due to this, all the previous data are erased.
Writing a string or sequence of bytes (for binary files) is done using
the write() method. This method returns the number of characters
written to the file.
This program will create a new file named test.txt in the current
directory if it does not exist. If it does exist, it is overwritten.
We must include the newline characters ourselves to distinguish the
different lines.
2/27/2023 Ms.S. Shanmuga Priya, AP/CSE, Vel Tech 45
Write to a Python File
• In order to write data into a file, we must open the file in write
mode.
• We need to be very careful while writing data into the file as it
overwrites the content present inside the file that you are writing,
and all the previous data will be erased.
• We have two methods for writing data into a file as shown below.
– write(string)
– writelines(list)
• Example 1:
my_file = open(“C:/Documents/Python/test.txt”, “w”)
my_file.write(“Hello World”)
The above code writes the String ‘Hello World’ into the ‘test.txt’
file.
Write to a Python File
Example 2:
my_file = open(“C:/Documents/Python/test.txt”, “w”)
my_file.write(“Hello World\n”)
my_file.write(“Hello Python”)
•The first line will be ‘Hello World’ and as we have mentioned \n character, the
cursor will move to the next line of the file and then write ‘Hello Python’.
•Remember if we don’t mention \n character, then the data will be written
continuously in the text file like ‘Hello WorldHelloPython’
Example 3:
fruits = *“Apple\n”, “Orange\n”, “Grapes\n”, “Watermelon”+
my_file = open(“C:/Documents/Python/test.txt”, “w”)
my_file.writelines(fruits)
The above code writes a list of data into the ‘test.txt’ file simultaneously.
Append in a Python File
Example 1:
my_file = open(“C:/Documents/Python/test.txt”, “a+”)
my_file.write (“Strawberry”)
The above code appends the string ‘Strawberry’ at the end of the ‘test.txt’ file
Example 2:
my_file = open(“C:/Documents/Python/test.txt”, “a+”)
my_file.write (“\nGuava”)
• read() and readline() reads data from file and return it in the
form of string and readlines() returns data in the form of list.
• All these read function also read leading and trailing
whitespaces, new line characters. If you want to remove these
characters you can use functions
– strip() : removes the given character from both ends.
– lstrip(): removes given character from left end
– rstrip(): removes given character from right end
Removing w hitespaces after readin g
f rom file
• Example: strip(), lstrip(), rstrip()
Fi l e P o i n t e r
• Every file maintains a file pointer which tells the current position in
the file where reading and writing operation will take.
• When we perform any read/write operation two things happens:
– The operation at the current position of file pointer
– File pointer advances by the specified number of bytes.
Fi l e Po i nte r
myfile = open(“ipl.txt”,”r”)
ch = myfile.read(1
ch will store first character i.e. first character is
consumed, and file pointer will move to next character
C.Closing the file
When we are done with performing operations on the file, we need
to properly close the file.
Closing a file will free up the resources that were tied with the file.
This is done using the close() method available in Python.
Python has a garbage collector to clean up unreferenced objects but
we must not rely on it to close the file.
• After processing the content in a file, the file must be saved and
closed. To do this we can use another method close() for closing the
file. This is an important method to be remembered while handling
files in python.
• Syntax: file_object.close()
Output
Output
Output
• Example dump()
:
• Example: load()
Binary file oper a tions
The four major operations performed using a binary file are—
• 1. Inserting/Appending a record in a binary file
• 2. Reading records from a binary file
• 3. Searching a record in a binary file
• 4. Updating a record in a binary file
Binary file oper a tions
• Once the record is found, the file pointer is moved to the beginning
of the file using seek(0) statement, and then the changed values are
written to the file and the record is updated. seek() method is used for
random access to the file.
B i n a r y f i l e o p e rat i o n s cont…5g
• Updating a record in a binary file
B i n a r y f i l e o p e rat i o n s cont…6
If, however, you pass a hexadecimal string to int(), then you’ll see a
ValueError.
The error message says that the string is not a valid decimal integer.
The argument that you pass to base is not limited to 2, 8, 10, and 16.
^a...s$
The above code defines a RegEx pattern. The pattern is: any five
letter string starting with a and ending with s.
import re
txt = "The rain in Spain"
#Check if the string starts with "The":
x = re.findall("\AThe", txt)
print(x)
if x:
print("Yes, there is a match!")
else:
print("No match")
OUTPUT:
['The']
Yes, there is a match!
2/27/2023 124
Special Sequences
Example:
txt = "The rain in Spain"
2/27/2023 125
Sets
A set is a set of characters inside a pair of square brackets [] with a special meaning:
Set Description
[arn] Returns a match where one of the specified characters (a, r, or n) is
present
[a-n] Returns a match for any lower case character, alphabetically
between a and n
[^arn] Returns a match for any character EXCEPT a, r, and n
[0123] Returns a match where any of the specified digits (0, 1, 2, or 3) are present
[a-zA-Z] Returns a match for any character alphabetically between a and z, lower
case OR upper case
[+] In sets, +, *, ., |, (), $,{} has no special meaning, so [+] means: return a
match for any + character in the string
2/27/2023 126
Sets
Example:
txt = "The rain in Spain"
x = re.findall("[^arn]", txt) # ['T', 'h', 'e', ' ', 'i', ' ', 'i', ' ', 'S', 'p', 'i']
x = re.findall("[a-n]", txt) #['h', 'e', 'a', 'i', 'n', 'i', 'n', 'a', 'i', 'n']
2/27/2023 127
Specify Pattern Using RegEx
re.findall()
• The re.findall() method returns a list of strings containing all
matches.
import re
string = 'Twelve:12 Eighty nine:89.'
pattern = '\d+‘
result = re.split(pattern, string)
print(result)
# Output: ['Twelve:', ' Eighty nine:', '.']
import re
string = 'abc 12 e 23 f45 6‘
# matches all whitespace characters
pattern = '\s+‘
# empty string
replace = '‘
new_string = re.sub(pattern, replace, string)
print(new_string)
# Output: abc12de23f456
import re
string = '39801 356, 2102 1111‘
# Three digit number followed by space followed by two digit number
pattern = '(\d{3}) (\d{2})‘
# match variable contains a Match object.
match = re.search(pattern, string)
if match:
print(match.group())
else:
print("pattern not found")
# Output: 801 35
import re
string = '39801 356, 2102 1111‘
# Three digit number followed by space followed by two digit number
pattern = '(\d{3}) (\d{2})‘
# match variable contains a Match object.
match = re.search(pattern, string)
if match:
print(match.group())
else:
print("pattern not found")
# Output: 801 35
2/27/2023 135
Example
import re
txt = "The rain in Spain"
x = re.search(r"\bS\w+", txt)
print(x.span()) #OUTPUT: (12,19)
Y = re.search(r"\bS\w+", txt)
print(Y.string) # OUTPUT: The rain in Spain
z = re.search(r"\bS\w+", txt)
print(z.group()) # output: Spain
2/27/2023 136
Python Decorators
• As mentioned earlier, A Python decorator is a function that takes in a
function and returns it by adding some functionality.
• In fact, any object which implements the special __call__() method is
termed callable. So, in the most basic sense, a decorator is a callable that
returns a callable.
• Basically, a decorator takes in a function, adds some functionality and
returns it.
def make_pretty(func):
def inner():
print("I got decorated")
func()
return inner
def ordinary():
print("I am ordinary")
# Output: I am ordinary
def inner():
print("I got decorated")
func()
return inner
@make_pretty
def ordinary():
print("I am ordinary")
ordinary()
2/27/2023 Ms.S. Shanmuga Priya, AP/CSE, Vel Tech 139
Decorating Functions with Parameters
def smart_divide(func):
def inner(a, b):
print("I am going to divide", a, "and", b)
if b == 0:
print("Whoops! cannot divide")
return
return func(a, b)
return inner
@smart_divide
def divide(a, b):
print(a/b)
divide(2,5)
divide(2,0)