Data Structures and Algorithms using Python | Part 2
Files:
A file is a location or information stored in computer storage devices. File handling is essential when the information or the data is to be held permanently.
When we try to implement the files program in other languages, it is very lengthy compared to Python. In Python, the execution of files is more accessible and shorter.
In Python, the files are created in two modes one is text and the other in binary mode. Every line of the file must be ended with special characters.
There are mainly three file operations that can be done in a particular order.
- Open a file
- Read or Write – operations
- Close the file
Opening a File:
When we have created a new file and want to open that file, then we use an open() function, which intakes two arguments, file name and access mode. This capability will return a document object used to perform different tasks like perusing, composing, and so forth.
Syntax:
File = open(<file-name>, <access-mode>, <buffering>)
There are some access modes to open a file. They are
"r":
This mode opens the record to peruse just mode. This record pointer generally exists toward the start. In this mode, as a matter of course, the record is open.
"rb":
This mode opens a document to peruse just in the parallel organisation. This document pointer generally exists toward the start.
“r+”:
This mode opens the file in both modes to read and write. This file pointer always exists at the beginning.
“rb+”:
This mode opens the file to read and write in binary mode. This file pointer always exists at the beginning.
“w”:
This mode opens the file to write-only mode. This file pointer always exists at the beginning. The write mode overwrites the file if any previous files exist.
“wb”:
This mode opens the file to the write-only mode in binary format. This file pointer always exists at the beginning.
“w+”:
This mode opens the file in both modes to read and write. This file pointer always exists at the beginning. It is different from “r+” because “r+” doesn’t overwrite the previous file, if any exist.
“wb+”:
This mode opens the file in both modes to read and write in binary mode. This file pointer always exists at the beginning.
“a”:
This mode opens the file in the append mode. This file pointer exists at the end of the file. If no files exist, it will create a new file in binary format if no other files with the same name exist.
“ab”:
This mode opens the file in the append mode in binary format. This file pointer exists at the end of the file. If no files exist, it will create a new file in binary format if no other files with the same name exist.
“a+”:
This mode opens the file in the append mode and reads mode. This file pointer exists at the end of the file. If no files exist, it will create a new file in binary format if no other files with the same name exist.
“ab+”:
This mode opens the file in the append mode and reads both in binary format. This file pointer exists at the end of the file. If no files exist, it will create a new file in binary format if no other files with the same name exist.
Example:
#simple program to open the file in the read mode
fp = open(“f.txt”, ”r”)
if fp:
print(“The file is opened successfully in the read mode”)
Output:
<class ‘_io. TextIOWrapper’ >
The file is opened successfully in the read mode.
Explanation:
“f.txt” is the file name and a text file. We have opened the file in reading mode. After that, we have given an if block, and if the statement is true, the print statement will be printed.
Close() Method:
After completing all the operations, like reading and writing on the file, we must close the file using the close() method. If any unwritten information is present in the file, all that information will be destroyed after using the close() method.
Syntax:
fileobject.close()
Example:
#simple program to open the file in the read mode
fp = open(“f.txt”, ”r”)
if fp:
print(“The file is opened successfully in the read mode”)
#closing the file that is opened
fp.close()
Once the file is closed, we can’t perform any operations on the files. We have to close the file correctly, i.e., after completing all the operations or functions like reading and writing on the files, we only have to close the file.
The “with” Statement:
If we want to manipulate files, we must use the “with” statement. The with
statement will be available only from Python 2.5 versions, and we can’t use “with.”
statement in the lower versions of the Python. “with” statement is used when a pair
of statements is executed with a block between the files.
Syntax:
with open(<name of the file>, <the mode to be accessed>) as <file-pointer>:
#statements to be executed
Using of “with” statement is always helpful in the program, mainly in the case of files
because if there are any mistake or error occurs in our program or any particular
block of code like a break, return, or exceptions, then the “with” statement
automatically close the file without using the close() method. And the file will not be
corrupted.
Example:
With open(“f.txt”, “r”) as fp: #opening a file named “f.txt” in the read mode
C = fp.read() #reading some text into c
print(c) #printing the previously stored data of the c
Writing the File:
In Python, if we want to write some text to a file, then firstly, we have to open the file
using the open() method with any of the following access modes
W:
This mode opens the file to write-only mode. This file pointer always exists at the
beginning. The write mode overwrites the file if any previous files exist.
a:
This mode opens the file in the append mode. This file pointer exists at the end of
the file. If no files exist, it will create a new file in binary format if no other files with
the same name exist.
Read a File:
We can use the read() method in Python to read a file. This method is used to read
the string form of the file. The read() method can read the data in text and binary formats.
Syntax:
fileobject.read( < count > )
In the above syntax, the count is used to specify the number of bytes to be read from
the file. It always starts considering the bytes from the beginning of the file. In the
read() method, if we forget to give a count, it will read the whole content of the
file.
Example:
#simple program to read the content of the file and print it
fp = open("f.txt","r")
#all the data of the file will be stored in the variable c
c = fp.read(10)
#printing the type of data stored in the file
print(type(c))
#printing the c of the file
print(c)
#closing the opened file
fp.close()
Output
<class ‘str’>
Java is an
Explanation:
We have opened a file in the reading mode in the above program. We have read the content of f.txt by using the read() method or function. In the above program, we have passed the count value as ten, i.e., the content will store only the first ten characters from the file.
c = fp.read()
print(c)
If we give the read function as above, it will read all the file characters. And the output will be
Output:
Java is an object-oriented programming language.
Reading File through for Loop:
Without using any other variable, we can directly print the file’s data using the for loop.
Example:
#simple program to print the file data using the for loop
fp = open(“f.txt”, “r”);
#printing the file’s data using for loop
For i in fp:
Print(i) # I contains all the lines available in the file
Output:
Java is an object-oriented programming language.
Readline() Method:
Python provides a readline() method which reads the file line by line. We use the readline() method instead of loops. This function reads the file from the beginning.
If we want to print the first line of the file, we will write the single readline() method, and to print the two lines of the file, we will write two readline() ways.
Example:
#simple program to print the file data using the readline() method
fp = open(“f.txt”, “r”);
c = fp.readline() #c stores the first line of the file
print(c) #print the first line of the file
Output:
Java is an object-oriented programming language.
Reading Lines of the file using the readlines() function:
Using the readline() function or method, we can read only a single line of the file but using the readlines() function or form, we can read all the lines of the file.
Example:
#simple program to read the lines of the file using the readlines() function
fp = open(“f.txt”, “r”);
#declaring a variable to store all the lines of the file using the readlines() function
C = fp.readlines()
#printing the lines stored in the variable c of the file
Pint(c)
#closing the file “f.txt.”
fp.close()
Output:
Java is an object-oriented programming language.
Creating a New File:
We can create a new file in Python using any one of the below access modes by using the function open().
x:
This access mode creates a new file with the specified name. If any file exists with the same name, then it will cause an error.
a:
This access mode creates a new file with the specified name if there is no other file that exists with the same name. This access mode appends the file’s content if any file already exists with the specified name.
w:
This access mode creates a new file with the specified name if there is no other file that exists with the same name. This access mode overwrites the existing file if any file exists with the same name.
Example:
#simple program to create a new file
fp1 = open("f2.txt","x")
print(fp1)
if fp1:
print("The new File has been created successfully")
Output:
<_io.TextIOWrapper name='file2.txt' mode='x' encoding='cp1252'>
The new file has been created successfully
Renaming the file:
The Python os module is used to interact with the operating system. The os module provides many functions involved in file processing operations like renaming, deleting, etc. The os module provides the rename() method to rename the specified file to a new name. The syntax to use the rename() method is provided below.
Syntax:
rename(present name of the file, new name of the file)
Example:
#simple program to change the name of the existing file
import os
#changing the name of the file using the rename() method
os.rename("f1.txt","f2.txt")
Explanation:
The above program is used to change or rename the existing file name. The current file name is “f1.txt”, and the file name has been changed to “f2.txt”.
Removing the File:
The os module provides the remove() method, which is used to remove the specified file. The syntax to use the remove() method is given below.
Syntax:
Remove(file name which we have to remove)
Example:
#simple program to remove the file
import os
os.remove(“f2.txt”)
Explanation:
The above program is used to remove the existing file. The current file, “f2.txt”, will be removed.
Sets:
A set is defined as an unordered collection of items. Every element in the set must be unique and immutable. The sets do not contain duplicate elements. Sets are mutable, which means we can modify them after their creation.
In sets, no index is attached to the elements of the set, i.e., we cannot directly access any element of the set by the index. We can print Sets of data altogether or get the list of elements by looping through the set.
Creating a Set:
The set can be created by enclosing the elements with a comma with the curly brackets “{}”. The components of the set must be unique, i.e., there will be no duplicate elements present in the sets.
Example:
#simple program to create a set with some data
n = {“John”, “Jack”, “smith”, “Simon”, “Boss”}
#we have created a set and stored the set data in the variable “n”.
print(type(n)) #printing the type of the variable “n”
print(“printing the elements of the set:”)
print(n)
Output:
<class ‘set’>
Printing the elements of the set:
{“John”, “Jack”, “smith”, “Simon”, “Boss”}
Example 1:
#simple program to create a set and to print using loops
n = {“John”, “Jack”, “smith”, “Simon”, “Boss”}
#we have created a set and stored the set data in the variable “n”.
print(type(n)) #printing the type of the variable “n”
print(“printing the elements of the set using the for loop:”)
for i in n:
print(i)
Output:
<class ‘set’>
Printing the elements of the set using the for loop:
John
Jack
Smith
Simon
Boss
We can also use the set() method to create the set.
Example:
#simple program to create a set and to print using loops
n = set({“John”, “Jack”, “smith”, “Simon”, “Boss”})
#we have created a set and stored the set data in the variable “n”.
print(type(n)) #printing the type of the variable “n”
print(“printing the elements of the set:”)
print(n)
print(“printing the elements of the set using the for loop:”)
for i in n:
print(i)
Output:
<class ‘set’>
Printing the elements of the set:
{“John”, “Jack”, “smith”, “Simon”, “Boss”}
Printing the elements of the set using the for loop:
John
Jack
Smith
Simon
Boss
Adding Elements or Items to the Set:
If we want to add elements to the set, we can use the add() method and update() method in some cases or situations.
add():
This method is used to add elements or items to the set. We can add only one element at a time using the add() method.
Example:
#simple program to add items to the set using the add() method
n = set({“John”, “Jack”, “smith”, “Simon”, “Boss”})
#we have created a set and stored the set data in the variable “n”.
print(type(n)) #printing the type of the variable “n”
print(“printing the elements of the set before adding the elements or items:”)
print(n)
print(“Adding the elements to the set using the add() method”)
n.add(“Vijay”)
n.add(“Pavan”)
print(“printing the elements of the set after adding the elements or items:”)
print(n)
print(“printing the elements of the set using the for loop:”)
for i in n:
print(i)
Output:
<class ‘set’>
Printing the elements of the set before adding the elements or items:
{“John”, “Jack”, “smith”, “Simon”, “Boss”}
Adding the elements to the set using the add() method
Printing the elements of the set after adding the elements or items:
{“John”, “Jack”, “smith”, “Simon”, “Boss”, “Vijay”, “Pavan”}
Printing the elements of the set using the for loop:
John
Jack
Smith
Simon
Boss
Vijay
Pavan
update():
This method is used to add elements or items to the set. We can add multiple elements simultaneously using the update() method.
Example:
#simple program to add items to the set using the update() method
n = set({“John”, “Jack”, “smith”, “Simon”, “Boss”})
#we have created a set and stored the set data in the variable “n”.
print(type(n)) #printing the type of the variable “n”
print(“printing the elements of the set before adding the elements or items:”)
print(n)
print(“adding the elements to the set using the update() method”)
n.update([“Amit”, “Sonu”, “Anil”])
print(“printing the elements of the set after adding the elements or items:”)
print(n)
print(“printing the elements of the set using the for loop:”)
for i in n:
print(i)
Output:
<class ‘set’>
Printing the elements of the set before adding the elements or items:
{“John”, “Jack”, “smith”, “Simon”, “Boss”}
Adding the elements to the set using the update() method
Printing the elements of the set after adding the elements or items:
{“John”, “Jack”, “smith”, “Simon”, “Boss”, “Amit”, “Sonu”, “Anil”}
Printing the elements of the set using the for loop:
John
Jack
Smith
Simon
Boss
Amit
Sonu
Anil
Removing Items from the Set:
In sets, If we want to remove any element from the sets, we can use two methods. They are
discard() Method:
This method is used to remove elements or items from the sets. This method will not through any error if the element or items given in the method are not present in the set.
Example:
#simple program to remove items from the set using the discard() method
n = set({“John”, “Jack”, “smith”, “Simon”, “Boss”})
#we have created a set and stored the set data in the variable “n”.
print(type(n)) #printing the type of the variable “n”
print(“printing the elements of the set before removing the elements or items:”)
print(n)
print(“Removing the elements of the set”)
n.discard(“Boss”)
n.discard(“John”)
print(“printing the elements of the set after removing the elements or items:”)
print(n)
print(“printing the elements of the set using the for loop:”)
for i in n:
print(i)
Output:
<class ‘set’>
Printing the elements of the set before removing the elements or items:
{“John”, “Jack”, “smith”, “Simon”, “Boss”}
Removing the elements of the set
Printing the elements of the set after removing the elements or items:
{“Jack”, “smith”, “Simon”}
Printing the elements of the set using the for loop:
Jack
Smith
Simon
remove() Method:
This method is used to remove elements or items from the sets. This method will through the error if the element or items given in the method are not present in the set.
Example:
#simple program to remove items from the set using the remove() method
n = set({“John”, “Jack”, “smith”, “Simon”, “Boss”})
#we have created a set and stored the set data in the variable “n”.
print(type(n)) #printing the type of the variable “n”
print(“printing the elements of the set before removing the elements or items:”)
print(n)
print(“removing the elements of the set using the remove() method”)
n.remove(“Boss”)
n.remove(“John”)
print(“printing the elements of the set after removing the elements or items:”)
print(n)
print(“printing the elements of the set using the for loop:”)
for i in n:
print(i)
Output:
<class ‘set’>
Printing the elements of the set before removing the elements or items:
{“John”, “Jack”, “smith”, “Simon”, “Boss”}
Removing the elements of the set using the remove() method
Printing the elements of the set after removing the elements or items:
{“Jack”, “smith”, “Simon”}
Printing the elements of the set using the for loop:
Jack
Smith
Simon
pop() Method:
This method is used to remove the items from the sets. Generally, the pop() method removes the last element, but the set is unordered, i.e., the elements don’t follow any particular order. In sets, we can’t determine the element popped.
Example:
#simple program to remove items from the set using the pop() method
n = set({“John”, “Jack”, “smith”, “Simon”, “Boss”})
#we have created a set and stored the set data in the variable “n”.
print(type(n)) #printing the type of the variable “n”
print(“printing the elements of the set before removing the elements or items:”)
print(n)
print(“removing the elements of the set using the pop() method”)
n.pop()
n.pop()
print(“printing the elements of the set after removing the elements or items:”)
print(n)
print(“printing the elements of the set using the for loop:”)
for i in n:
print(i)
Output:
<class ‘set’>
Printing the elements of the set before removing the elements or items:
{“John”, “Jack”, “smith”, “Simon”, “Boss”}
Removing the elements of the set using the pop() method
Printing the elements of the set after removing the elements or items:
{“smith”, “Simon”, “Boss”}
Printing the elements of the set using the for loop:
Smith
Simon
Boss
Explanation:
In the above program, the pop() method removed the first two elements, i.e., “John” and “Jack”, instead of the last ones, i.e., “Simon” and “Boss”, because the sets are unordered.
clear() Method:
In sets, the clear() method removes all the elements or items from the sets.
Example:
#simple program to remove items from the set using the clear() method
n = set({“John”, “Jack”, “smith”, “Simon”, “Boss”})
#we have created a set and stored the set data in the variable “n”.
print(type(n)) #printing the type of the variable “n”
print(“printing the elements of the set before removing the elements or items:”)
print(n)
print(“removing the elements of the set using the clear() method:”)
n.clear()
print(“printing the elements of the set after removing the elements or items:”)
print(n)
Output:
<class ‘set’>
Printing the elements of the set before removing the elements or items:
{“John”, “Jack”, “smith”, “Simon”, “Boss”}
Removing the elements of the set using the clear() method
Printing the elements of the set after removing the elements or items:
{“smith”, “Simon”, “Boss”}
Set Operations:
We can perform mathematical operations on sets like Union, intersection, difference, and symmetric difference. In Python, we can use these as operators and also the methods.
Union of two Sets:
We can perform the union operation using the symbol pipe(|) operator and the union() method. The union of two sets contains all the available items of both sets.
Example:
#simple program to perform union operation using the pipe(|) operator
S1 = {“Vijay”, “Sai”, “John”} #creating a set s1 that contains three items
S2 = {“Kumar”, “Pavan”, “Jack”} # creating a set s2 that contains three items
print(“Printing the items of the set after performing the union operation using the pipe(|) operator”)
print(s1|s2)
Output:
Printing the items of the set after performing the union operation using the pipe(|) operator
{‘Vijay’, ‘Sai’, ‘John’, ‘Kumar’, ‘Pavan’, ‘Jack’}
Example 1:
#simple program to perform union operation using the union() method
S1 = {“Vijay”, “Sai”, “John”} # creating a set s1 that contains three items
S2 = {“Kumar”, “Pavan”, “Jack”} # creating a set s2 that contains three items
Print(“Printing the items of the set after performing the union operation using the union() method”)
Print(s1.union(s2))
Output:
Printing the items of the set after performing the union operation using the union() method
{‘Vijay’, ‘Sai’, ‘John’, ‘Kumar’, ‘Pavan’, ‘Jack’}
Intersecting of two Sets:
We can perform the intersection operation using the symbol and(&) operator and the intersection() method. The intersection of two sets can be given as a set that contains common items of both sets.
Example:
#simple program to perform intersection operation using the and(&) operator
S1 = {“Vijay”, “Sai”, “John”, “Jack”} #creating a set s1 that contains four items.
S2 = {“Sai”, “Kumar”, “Pavan”, “Jack”} # creating a set s2 that contains four items.
Print(“Printing the items of the set after performing the intersection operation using the and(&) operator”)
Print(s1&s2)
Output:
Printing the items of the set after performing the intersection operation using the and(&) operator.
{‘Sai’, ‘Jack’}
Example 1:
#simple program to perform intersection operations using the intersection() method
S1 = {“Vijay”, “Sai”, “John”, “Jack”} #creating a set s1 that contains four items.
S2 = {“Sai”, “Kumar”, “Pavan”, “Jack”} # creating a set s2 that contains four items.
Print(“Printing the items of the set after performing the intersection operation using the intersection() method”)
Print(s1.intersection(s2))
Output:
Printing the items of the set after performing the intersection operation using the intersection() method.
{‘Sai’, ‘Jack’}
Difference between the two Sets:
Python provides the subtraction(-) operator or the difference() method to perform the difference between the two sets. Consider there are two sets, s1 and s2, and the difference is given by s1-s2, which denotes the resulting set will be obtained from the element of s1, which is not present in set s2.
Example:
#simple program to perform difference between two sets using the subtraction(-) #operator
S1 = {“Vijay”, “Sai”, “John”, “Jack”} #creating a set s1 that contains four items.
S2 = {“Sai”, “Kumar”, “Pavan”, “Jack”} # creating a set s2 that contains four items.
print(“Printing the items of the set after performing the difference between the two sets using the subtraction(-) operator”)
print(s1-s2)
Output:
Printing the items of the set after performing the difference between the two sets using the subtraction(-) operator
{‘Vijay’, ‘John’}
Example 1:
#simple program to perform difference between two sets using the difference() #method
S1 = {“Vijay”, “Sai”, “John”, “Jack”} #creating a set s1 that contains four items.
S2 = {“Sai”, “Kumar”, “Pavan”, “Jack”} # creating a set s2 that contains four items.
print(“Printing the items of the set after performing the difference between the two sets using the difference() method”)
print(s1.difference(s2))
Output:
Printing the items of the set after performing the difference between the two sets using the difference() method
{‘Vijay’, ‘John’}
Symmetric Difference between two Sets:
We can perform or calculate the symmetric difference between two sets using the “^”’ operator or symmetric_difference() method. This operator will remove the common elements of both sets and print the remaining elements of both sets.
Example:
#simple program to perform difference between two sets using the ^ operator
S1 = {“Vijay”, “Sai”, “John”, “Jack”} #creating a set s1 that contains four items.
S2 = {“Sai”, “Kumar”, “Pavan”, “Jack”} # creating a set s2 that contains four items.
S3=s1^s2
print(“Printing the items of the set after performing the symmetric difference between the two sets using the ^ operator”)
print(s3)
print(“Printing the output using the for loop”)
for i in s3
print(i)
Output:
Printing the items of the set after performing the symmetric difference between the two sets using the ^ operator
{‘Vijay’, ‘John’, ‘Kumar’, ‘Pavan’}
Printing the output using the for loop
Vijay
John
Kumar
Pavan
Example 1:
#simple program to perform difference between two sets using the #symmetric_difference() method
S1 = {“Vijay”, “Sai”, “John”, “Jack”} #creating a set s1 that contains four items.
S2 = {“Sai”, “Kumar”, “Pavan”, “Jack”} # creating a set s2 that contains four items.
S3=s1.symmetric_difference(s2)
print(“Printing the items of the set after performing the symmetric difference between the two sets using the ^ operator”)
print(s3)
print(“Printing the output using the for loop”)
for i in s3
print(i)
Output:
Printing the items of the set after performing the symmetric difference between the two sets using the symmetric_difference() method
{‘Vijay’, ‘John’, ‘Kumar’, ‘Pavan’}
Printing the output using the for loop
Vijay
John
Kumar
Pavan
Set Comparisons:
Python permits us to utilise the correlation administrators, i.e., <, >, <=, >=, == with the sets by which we can check whether a set is a set, superset, or comparable to others. The boolean valid or misleading is returned relying on the things inside the sets.
Example:
#simple program to perform or compare multiple sets
S1 = {“Vijay”, “Sai”, “John”, “Jack”} #creating a set s1 that contains four items.
S2 = {“Sai”, “John”, “Vijay”} # creating a set s2 that contains three items.
S3= {“David”, “Srikanth”} #creating a set s3 that contains two items
print(s1>s2)
print(s1<s2)
print(s2==s3)
Output:
True
False
False
Explanation:
The first print statement will give the output as true because the set s1 is the superset of s2, i.e., the set s2 will contain all the elements of the set s1, but the s1 set will not have all the details of the set s2. And the second print statement will print false because the s1 set is not the subset of the set s2. Last print statement prints the output as false because the set s2 and the set s3 are not equivalent, i.e., they do not contain an equal no of items.
Frozen Sets:
The frozen sets are the permanent type of the typical sets, i.e., the things of the frozen set can't be changed, and hence it tends to be utilised as a vital in the word reference.
The components of the frozen set can't be changed after the creation. We can't change or add the substance of the frozen sets by utilising techniques like add() or eliminate(). The frozenset() technique or method is used to make the frozenset object. The iterable grouping is passed into this technique which is changed over into the frozen set as a return kind of strategy.
Example:
#simple program for frozen sets
Fz = frozenset([21, 22, 23, 24, 25])
print(type(Fz))
print(“Printing the items or data of frozen sets using the for loop:”)
for i in Fz:
print(i)
Output:
<class ‘frozenset’>
Printing the items or data of frozen sets using the for loop:
21
22
23
24
25
Frozen Sets for the Dictionary:
Assuming that we pass the word reference as the grouping inside the frozenset() technique, it will take just the keys from the word reference and return a frozenset containing the key of the word reference as its components.
Example:
D = {"Name": "Vijay", "Age": "20", "Gender": “M”}
print(type(D))
Fs = frozenset(Dictionary) #Fs will contain the keys of the dictionary
print(type(Fs))
for i in Fs:
print(i)
Output:
<class ‘dict’>
<class ‘frozenset’>
Name
Age
Gender