Python Introduction
Python Introduction
An object-oriented paradigm is to design the program using classes and objects. The
object is related to real-word entities such as book, house, pencil, etc. The oops
concept focuses on writing the reusable code. It is a widespread technique to solve
the problem by creating objects.
o Inheritance: When one object acquires all the properties and behaviors of a
parent object, it is known as inheritance. It provides code reusability
o Polymorphism : If one task is performed in different ways, it is known as
polymorphism.
o Data Abstraction: Hiding internal details and showing functionality is known
as abstraction. For example phone call, we don't know the internal
processing.
o Encapsulation: Binding (or wrapping) code and data together into a single
unit are known as encapsulation. For example, a capsule, it is wrapped with
different medicines.
Class
The class can be defined as a collection of objects. It is a logical entity that has
some specific attributes and methods. For example: if you have an employee class,
then it should contain an attribute and method, i.e. an email id, name, age, salary,
etc.
Syntax
1. class ClassName:
2. <statement-1>
3. .
4. .
5. <statement-N>
Object
The object is an entity that has state and behavior. It may be any real-world object
like the mouse, keyboard, chair, table, pen, etc.
Example:
1. class car:
2. def __init__(self,modelname, year):
3. self.modelname = modelname
4. self.year = year
5. def display(self):
6. print(self.modelname,self.year)
7.
8. c1 = car("Toyota", 2016)
9. c1.display()
Output:
Toyota 2016
In the above example, we have created the class named car, and it has two
attributes modelname and year. We have created a c1 object to access the class
attribute. The c1 object will allocate memory for these values. We will learn more
about class and object in the next tutorial.
Method
The method is a function that is associated with an object. In Python, a method is
not unique to class instances. Any object type can have methods.
Inheritance
Inheritance is the most important aspect of object-oriented programming, which
simulates the real-world concept of inheritance. It specifies that the child object
acquires all the properties and behaviors of the parent object.
By using inheritance, we can create a class which uses all the properties and
behavior of another class. The new class is known as a derived class or child class,
and the one whose properties are acquired is known as a base class or parent class.
Polymorphism
Polymorphism contains two words "poly" and "morphs". Poly means many, and
morph means shape. By polymorphism, we understand that one task can be
performed in different ways. For example - you have a class animal, and all animals
speak. But they speak differently. Here, the "speak" behavior is polymorphic in a
sense and depends on the animal. So, the abstract "animal" concept does not
actually "speak", but specific animals (like dogs and cats) have a concrete
implementation of the action "speak".
Encapsulation
Encapsulation is also an essential aspect of object-oriented programming. It is used
to restrict access to methods and variables. In encapsulation, code and data are
wrapped together within a single unit from being modified by accident.
Data Abstraction
Data abstraction and encapsulation both are often used as synonyms. Both are
nearly synonyms because data abstraction is achieved through encapsulation.
Abstraction is used to hide internal details and show only functionalities. Abstracting
something means to give names to things so that the name captures the core of
what a function or a whole program does.
Syntax
1. class ClassName:
2. #statement_suite
In Python, we must notice that each class is associated with a documentation string
which can be accessed by using <class-name>.__doc__. A class contains a
statement suite including fields, constructor, function, etc. definition.
Consider the following example to create a class Employee which contains two
fields as Employee id, and name.
The class also contains a function display(), which is used to display the
information of the Employee.
Example
1. class Employee:
2. id = 10
3. name = "Devansh"
4. def display (self):
5. print(self.id,self.name)
Here, the self is used as a reference variable, which refers to the current class
object. It is always the first argument in the function definition. However,
using self is optional in the function call.
The self-parameter
The self-parameter refers to the current instance of the class and accesses the class
variables. We can use anything instead of self, but it must be the first parameter of
any function which belongs to the class.
1. <object-name> = <class-name>(<arguments>)
The following example creates the instance of the class Employee defined in the
above example.
Example
1. class Employee:
2. id = 10
3. name = "John"
4. def display (self):
5. print("ID: %d \nName: %s"%(self.id,self.name))
6. # Creating a emp instance of Employee class
7. emp = Employee()
8. emp.display()
Output:
ID: 10
Name: John
In the above code, we have created the Employee class which has two attributes
named id and name and assigned value to them. We can observe we have passed
the self as parameter in display function. It is used to refer to the same class
attribute.
We have created a new instance object named emp. By using it, we can access the
attributes of the class.
Example
1. class Employee:
2. id = 10
3. name = "John"
4.
5. def display(self):
6. print("ID: %d \nName: %s" % (self.id, self.name))
7. # Creating a emp instance of Employee class
8.
9. emp = Employee()
10.
11.# Deleting the property of object
12.del emp.id
13.# Deleting the object itself
14.del emp
15.emp.display()
It will through the Attribute error because we have deleted the object emp.
Python Constructor
A constructor is a special type of method (function) which is used to initialize the
instance members of the class.
In C++ or Java, the constructor has the same name as its class, but it treats
constructor differently in Python. It is used to create an object.
1. Parameterized Constructor
2. Non-parameterized Constructor
We can pass any number of arguments at the time of creating the class object,
depending upon the __init__() definition. It is mostly used to initialize the class
attributes. Every class must have a constructor, even if it simply relies on the
default constructor.
Example
1. class Employee:
2. def __init__(self, name, id):
3. self.id = id
4. self.name = name
5.
6. def display(self):
7. print("ID: %d \nName: %s" % (self.id, self.name))
8.
9.
10.emp1 = Employee("John", 101)
11.emp2 = Employee("David", 102)
12.
13.# accessing display() method to print employee 1 information
14.
15.emp1.display()
16.
17.# accessing display() method to print employee 2 information
18.emp2.display()
Output:
ID: 101
Name: John
ID: 102
Name: David
Example
1. class Student:
2. count = 0
3. def __init__(self):
4. Student.count = Student.count + 1
5. s1=Student()
6. s2=Student()
7. s3=Student()
8. print("The number of students:",Student.count)
Output:
Example
1. class Student:
2. # Constructor - non parameterized
3. def __init__(self):
4. print("This is non parametrized constructor")
5. def show(self,name):
6. print("Hello",name)
7. student = Student()
8. student.show("John")
Python Parameterized Constructor
The parameterized constructor has multiple parameters along with the self.
Consider the following example.
Example
1. class Student:
2. # Constructor - parameterized
3. def __init__(self, name):
4. print("This is parametrized constructor")
5. self.name = name
6. def show(self):
7. print("Hello",self.name)
8. student = Student("John")
9. student.show()
Output:
Example
1. class Student:
2. roll_num = 101
3. name = "Joseph"
4.
5. def display(self):
6. print(self.roll_num,self.name)
7.
8. st = Student()
9. st.display()
Output:
101 Joseph
More than One Constructor in Single class
Let's have a look at another scenario, what happen if we declare the two same
constructors in the class.
Example
1. class Student:
2. def __init__(self):
3. print("The First Constructor")
4. def __init__(self):
5. print("The second contructor")
6.
7. st = Student()
Output:
In the above code, the object st called the second constructor whereas both have
the same configuration. The first method is not accessible by the st object.
Internally, the object of the class will always call the last constructor if the class has
multiple constructors.
SN Function Description
Example
1. class Student:
2. def __init__(self, name, id, age):
3. self.name = name
4. self.id = id
5. self.age = age
6.
7. # creates the object of the class Student
8. s = Student("John", 101, 22)
9.
10.# prints the attribute name of the object s
11.print(getattr(s, 'name'))
12.
13.# reset the value of attribute age to 23
14.setattr(s, "age", 23)
15.
16.# prints the modified value of age
17.print(getattr(s, 'age'))
18.
19.# prints true if the student contains the attribute with name id
20.
21.print(hasattr(s, 'id'))
22.# deletes the attribute age
23.delattr(s, 'age')
24.
25.# this will give an error since the attribute age has been deleted
26.print(s.age)
Output:
John
23
True
AttributeError: 'Student' object has no attribute 'age'
Built-in class attributes
Along with the other attributes, a Python class also contains some built-in class
attributes which provide information about the class.
SN Attribute Description
Example
1. class Student:
2. def __init__(self,name,id,age):
3. self.name = name;
4. self.id = id;
5. self.age = age
6. def display_details(self):
7. print("Name:%s, ID:%d, age:%d"%(self.name,self.id))
8. s = Student("John",101,22)
9. print(s.__doc__)
10.print(s.__dict__)
11.print(s.__module__)
Output:
None
{'name': 'John', 'id': 101, 'age': 22}
__main__
Python Inheritance
Inheritance is an important aspect of the object-oriented paradigm. Inheritance
provides code reusability to the program because we can use an existing class to
create a new class instead of creating it from scratch.
In inheritance, the child class acquires the properties and can access all the data
members and functions defined in the parent class. A child class can also provide its
specific implementation to the functions of the parent class. In this section of the
tutorial, we will discuss inheritance in detail.
In python, a derived class can inherit base class by just mentioning the base in the
bracket after the derived class name. Consider the following syntax to inherit a base
class into the derived class.
Syntax
1. class derived-class(base class):
2. <class-suite>
A class can inherit multiple classes by mentioning all of them inside the bracket.
Consider the following syntax.
Example:
Python3
# Base class
class Parent:
def func1(self):
print("This function is in parent
class.")
# Derived class
class Child(Parent):
def func2(self):
print("This function is in child class.")
# Driver's code
object = Child()
object.func1()
object.func2()
Output:
Multiple Inheritance: When a class can be derived from more than one
base class this type of inheritance is called multiple inheritance. In multiple
inheritance, all the features of the base classes are inherited into the derived
class.
Example:
Python3
# Base class1
class Mother:
mothername = ""
def mother(self):
print(self.mothername)
# Base class2
class Father:
fathername = ""
def father(self):
print(self.fathername)
# Derived class
class Son(Mother, Father):
def parents(self):
print("Father :", self.fathername)
print("Mother :", self.mothername)
# Driver's code
s1 = Son()
s1.fathername = "RAM"
s1.mothername = "SITA"
s1.parents()
Output:
Father : RAM
Mother : SITA
Multilevel Inheritance
In multilevel inheritance, features of the base class and the derived class are
further inherited into the new derived class. This is similar to a relationship
representing a child and grandfather.
Example:
Python3
# Base class
class Grandfather:
# Intermediate class
class Father(Grandfather):
def __init__(self, fathername, grandfathername):
self.fathername = fathername
# Derived class
class Son(Father):
def __init__(self,sonname, fathername, grandfathername):
self.sonname = sonname
# invoking constructor of Father class
Father.__init__(self, fathername, grandfathername)
def print_name(self):
print('Grandfather name :', self.grandfathername)
print("Father name :", self.fathername)
print("Son name :", self.sonname)
# Driver code
s1 = Son('Prince', 'Rampal', 'Lal mani')
print(s1.grandfathername)
s1.print_name()
Output:
Lal mani
Grandfather name : Lal mani
Father name : Rampal
Son name : Prince
Hierarchical Inheritance: When more than one derived classes are created
from a single base this type of inheritance is called hierarchical inheritance.
In this program, we have a parent (base) class and two child (derived)
classes.
Example:
Python3
# Python program to demonstrate
# Hierarchical inheritance
# Base class
class Parent:
def func1(self):
print("This function is in parent class.")
# Derived class1
class Child1(Parent):
def func2(self):
print("This function is in child 1.")
# Derivied class2
class Child2(Parent):
def func3(self):
print("This function is in child 2.")
# Driver's code
object1 = Child1()
object2 = Child2()
object1.func1()
object1.func2()
object2.func1()
object2.func3()
Output:
This function is in parent class.
This function is in child 1.
This function is in parent class.
This function is in child 2.
Example:
Python3
class School:
def func1(self):
print("This function is in school.")
class Student1(School):
def func2(self):
print("This function is in student 1. ")
class Student2(School):
def func3(self):
print("This function is in student 2.")
class Student3(Student1, School):
def func4(self):
print("This function is in student 3.")
# Driver's code
object = Student3()
object.func1()
object.func2()
Output:
This function is in school.
This function is in student 1.
Method Overriding
We can provide some specific implementation of the parent class method in our child
class. When the parent class method is defined in the child class with some specific
implementation, then the concept is called method overriding. We may need to
perform method overriding in the scenario where the different definition of a parent
class method is needed in the child class.
Example
1. class Animal:
2. def speak(self):
3. print("speaking")
4. class Dog(Animal):
5. def speak(self):
6. print("Barking")
7. d = Dog()
8. d.speak()
Output:
Barking
Output:
Python3
print(1 + 2)
The answer is No, it cannot. Can you use the + operator to add two
objects of a class. The + operator can add two integer values, two
float values or can be used to concatenate two strings only because
these behaviours have been defined in python.
So if you want to use the same operator to add two objects of some
user defined class then you will have to defined that behaviour
yourself and inform python about that.
If you are still not clear, let's create a class and try to use
the + operator to add two objects of that class,
class Complex:
self.real = r
self.img = i
c1 = Complex(5,3)
c2 = Complex(2,4)
Overloading + operator
In the below code example we will overload the + operator for our
class Complex,
class Complex:
self.real = r
self.img = i
r = self.real + sec.real
i = self.img + sec.img
return complx(r,i)
def __str__(self):
c1 = Complex(5,3)
c2 = Complex(2,4)
print("sum = ",c1+c2)
sum = 7 + 7i
Python Modules
A python module can be defined as a python program file which contains a python
code including python functions, class, or variables. In other words, we can say that
our python code file saved with the extension (.py) is treated as the module. We
may have a runnable code inside the python module.
Modules in Python provides us the flexibility to organize the code in a logical way.
To use the functionality of one module into another, we must have to import the
specific module.
Example
In this example, we will create a module named as file.py which contains a function
func that contains a code to print some message on the console.
Here, we need to include this module into our main module to call the method
displayMsg() defined in the module named file.
We can import multiple modules with a single import statement, but a module is
loaded once regardless of the number of times, it has been imported into our file.
Hence, if we need to call the function displayMsg() defined in the file file.py, we have
to import that file as a module into our module as shown in the example below.
Example:
1. import file;
2. name = input("Enter the name?")
3. file.displayMsg(name)
Output:
Consider the following module named as calculation which contains three functions
as summation, multiplication, and divide.
calculation.py:
Main.py:
Output:
Renaming a module
Python provides us the flexibility to import some module with a specific name so
that we can use this name to use that module in our python source file.
Example
1. #the module calculation of previous example is imported in this example as c
al.
2. import calculation as cal;
3. a = int(input("Enter a?"));
4. b = int(input("Enter b?"));
5. print("Sum = ",cal.summation(a,b))
Output:
Enter a?10
Enter b?20
Sum = 30
Example
1. import json
2.
3. List = dir(json)
4.
5. print(List)
Output:
for example, to reload the module calculation defined in the previous example, we
must use the following line of code.
1. reload(calculation)
Scope of variables
In Python, variables are associated with two types of scopes. All the variables
defined in a module contain the global scope unless or until it is defined within a
function.
All the variables defined inside a function contain a local scope that is limited to this
function itself. We can not access a local variable globally.
If two variables are defined with the same name with the two different scopes, i.e.,
local and global, then the priority will always be given to the local variable.
Example
1. name = "john"
2. def print_name(name):
3. print("Hi",name) #prints the name that is local to this function only.
4. name = input("Enter the name?")
5. print_name(name)
Output:Hi David
Python packages
The packages in python facilitate the developer with the application development
environment by providing a hierarchical directory structure where a package
contains sub-packages, modules, and sub-modules. The packages are used to
categorize the application level code efficiently.
Let's create a package named Employees in your home directory. Consider the
following steps.
ITEmployees.py
1. def getITNames():
2. List = ["John", "David", "Nick", "Martin"]
3. return List;
3. Similarly, create one more python file with name BPOEmployees.py and create a
function getBPONames().
4. Now, the directory Employees which we have created in the first step contains
two python modules. To make this directory a package, we need to include one
more file here, that is __init__.py which contains the import statements of the
modules defined in this directory.
__init__.py
5. Now, the directory Employees has become the package containing two python
modules. Here we must notice that we must have to create __init__.py inside a
directory to convert this directory to a package.
6. To use the modules defined inside the package Employees, we must have to
import this in our python source file. Let's create a simple python source file at our
home directory (/home) which uses the modules defined in this package.
Test.py
1. import Employees
2. print(Employees.getNames())
Output:
We can have sub-packages inside the packages. We can nest the packages up to
any level depending upon the application requirements.
We don't usually store all of our files on our computer in the same location.
We use a well-organized hierarchy of directories for easier access.
Similar files are kept in the same directory, for example, we may keep all
the songs in the "music" directory. Analogous to this, Python has packages
for directories and modules for files.
As our application program grows larger in size with a lot of modules, we
place similar modules in one package and different modules in different
packages. This makes a project (program) easy to manage and
conceptually clear.
We can import modules from packages using the dot (.) operator.
For example, if we want to import the start module in the above example, it
can be done as follows:
import Game.Level.start
Game.Level.start.select_difficulty(2)
If this construct seems lengthy, we can import the module without the
package prefix as follows:
start.select_difficulty(2)
Another way of importing just the required function (or class or variable)
from a module within a package would be as follows:
select_difficulty(2)
Python Exception
An exception can be defined as an unusual condition in a program resulting in the
interruption in the flow of the program.
Whenever an exception occurs, the program stops the execution, and thus the
further code is not executed. Therefore, an exception is the run-time errors that are
unable to handle to Python script. An exception is a Python object that represents an
error
Python provides a way to handle the exception so that the code can be executed
without any interruption. If we do not handle the exception, the interpreter doesn't
execute all the code that exists after the exception.
Python has many built-in exceptions that enable our program to run without
interruption and give the output. These exceptions are given below:
Common Exceptions
Python provides the number of built-in exceptions, but here we are describing the
common standard exceptions. A list of common exceptions that can be thrown from
a standard Python program is given below.
1. ZeroDivisionError: Occurs when a number is divided by zero.
5. EOFError: It occurs when the end of the file is reached, and yet operations
are being performed.
Suppose we have two variables a and b, which take the input from the user and
perform the division of these values. What if the user entered the zero as the
denominator? It will interrupt the program execution and through
a ZeroDivision exception. Let's see the following example.
Example
1. a = int(input("Enter a:"))
2. b = int(input("Enter b:"))
3. c = a/b
4. print("a/b = %d" %c)
5.
6. #other code:
7. print("Hi I am other part of the program")
Output:
Enter a:10
Enter b:0
Traceback (most recent call last):
File "exception-test.py", line 3, in <module>
c = a/b;
ZeroDivisionError: division by zero
The above program is syntactically correct, but it through the error because of
unusual input. That kind of programming may not be suitable or recommended for
the projects because these projects are required uninterrupted execution. That's
why an exception-handling plays an essential role in handling these unexpected
exceptions. We can handle these exceptions in the following way.
Exception handling in python
The try-expect statement
If the Python program contains suspicious code that may throw the exception, we
must place that code in the try block. The try block must be followed with
the except statement, which contains a block of code that will be executed if there
is some exception in the try block.
Syntax
1. try:
2. #block of code
3.
4. except Exception1:
5. #block of code
6.
7. except Exception2:
8. #block of code
9.
10.#other code
Example 1
1. try:
2. a = int(input("Enter a:"))
3. b = int(input("Enter b:"))
4. c = a/b
5. except:
6. print("Can't divide with zero")
Output:
Enter a:10
Enter b:0
Can't divide with zero
We can also use the else statement with the try-except statement in which, we can
place the code which will be executed in the scenario if no exception occurs in the
try block.
The syntax to use the else statement with the try-except statement is given below.
1. try:
2. #block of code
3.
4. except Exception1:
5. #block of code
6.
7. else:
8. #this code executes if no except block is executed
Example 2
1. try:
2. a = int(input("Enter a:"))
3. b = int(input("Enter b:"))
4. c = a/b
5. print("a/b = %d"%c)
6. # Using Exception with except statement. If we print(Exception) it will return
exception class
7. except Exception:
8. print("can't divide by zero")
9. print(Exception)
10.else:
11. print("Hi I am else block")
Output:
Enter a:10
Enter b:0
can't divide by zero
<class 'Exception'>
Example
1. try:
2. a = int(input("Enter a:"))
3. b = int(input("Enter b:"))
4. c = a/b;
5. print("a/b = %d"%c)
6. except:
7. print("can't divide by zero")
8. else:
9. print("Hi I am else block")
1. try:
2. a = int(input("Enter a:"))
3. b = int(input("Enter b:"))
4. c = a/b
5. print("a/b = %d"%c)
6. # Using exception object with the except statement
7. except Exception as e:
8. print("can't divide by zero")
9. print(e)
10.else:
11. print("Hi I am else block")
Output:
Enter a:10
Enter b:0
can't divide by zero
division by zero
Points to remember
1. Python facilitates us to not specify the exception with the except statement.
2. We can declare multiple exceptions in the except statement since the try
block may contain the statements which throw the different type of
exceptions.
3. We can also specify an else block along with the try-except statement, which
will be executed if no exception is raised in the try block.
4. The statements that don't throw the exception should be placed inside the
else block.
Example
1. try:
2. #this will throw an exception if the file doesn't exist.
3. fileptr = open("file.txt","r")
4. except IOError:
5. print("File not found")
6. else:
7. print("The file opened successfully")
8. fileptr.close()
Output:
Syntax
1. try:
2. #block of code
3.
4. except (<Exception 1>,<Exception 2>,<Exception 3>,...<Exception n>)
5. #block of code
6.
7. else:
8. #block of code
1. try:
2. a=10/0;
3. except(ArithmeticError, IOError):
4. print("Arithmetic Exception")
5. else:
6. print("Successfully Done")
Output:
Arithmetic Exception
We can use the finally block with the try block in which we can pace the necessary
code, which must be executed before the try statement throws an exception.
Syntax
1. try:
2. # block of code
3. # this may throw an exception
4. finally:
5. # block of code
6. # this will always be executed
Example
1. try:
2. fileptr = open("file2.txt","r")
3. try:
4. fileptr.write("Hi I am good")
5. finally:
6. fileptr.close()
7. print("file closed")
8. except:
9. print("Error")
Output:
file closed
Error
Raising exceptions
An exception can be raised forcefully by using the raise clause in Python. It is useful
in in that scenario where we need to raise an exception to stop the execution of the
program.
For example, there is a program that requires 2GB memory for execution, and if the
program tries to occupy 2GB of memory, then we can raise an exception to stop the
execution of the program.
Syntax
1. raise Exception_class,<value>
Points to remember
1. To raise an exception, the raise statement is used. The exception class name
follows it.
3. To access the value "as" keyword is used. "e" is used as a reference variable
which stores the value of the exception.
Example
1. try:
2. age = int(input("Enter the age:"))
3. if(age<18):
4. raise ValueError
5. else:
6. print("the age is valid")
7. except ValueError:
8. print("The age is not valid")
Output:
1. try:
2. num = int(input("Enter a positive integer: "))
3. if(num <= 0):
4. # we can pass the message in the raise statement
5. raise ValueError("That is a negative number!")
6. except ValueError as e:
7. print(e)
Output:
Example 3
1. try:
2. a = int(input("Enter a:"))
3. b = int(input("Enter b:"))
4. if b is 0:
5. raise ArithmeticError
6. else:
7. print("a/b = ",a/b)
8. except ArithmeticError:
9. print("The value of b can't be 0")
Output:
Enter a:10
Enter b:0
The value of b can't be 0
Custom Exception
The Python allows us to create our exceptions that can be raised from the program
and caught using the except clause. However, we suggest you read this section after
visiting the Python object and classes.
Example
1. class ErrorInCode(Exception):
2. def __init__(self, data):
3. self.data = data
4. def __str__(self):
5. return repr(self.data)
6.
7. try:
8. raise ErrorInCode(2000)
9. except ErrorInCode as ae:
10. print("Received error:", ae.data)
Output:
Sometimes, it is not enough to only display the data on the console. The data to be
displayed may be very large, and only a limited amount of data can be displayed on
the console since the memory is volatile, it is impossible to recover the
programmatically generated data again and again.
The file handling plays an important role when the data needs to be stored
permanently into the file. A file is a named location on disk to store related
information. We can access the stored information (non-volatile) after the program
termination.
In Python, files are treated in two modes as text or binary. The file may be in the
text or binary format, and each line of a file is ended with the special character.
o Open a file
Opening a file
Python provides an open() function that accepts two arguments, file name and
access mode in which the file is accessed. The function returns a file object which
can be used to perform various operations like reading, writing, etc.
Syntax:
The files can be accessed using various modes like read, write, or append. The
following are the details about the access mode to open a file.
SN Access Description
mode
3 r+ It opens the file to read and write both. The file pointer
exists at the beginning of the file.
4 rb+ It opens the file to read and write both in binary format. The
file pointer exists at the beginning of the file.
8 wb+ It opens the file to write and read both in binary format. The
file pointer exists at the beginning of the file.
9 a It opens the file in the append mode. The file pointer exists
at the end of the previously written file if exists any. It
creates a new file if no file exists with the same name.
Let's look at the simple example to open a file named "file.txt" (stored in the same
directory) in read mode and printing its content on the console.
Example
1. #opens the file file.txt in read mode
2. fileptr = open("file.txt","r")
3.
4. if fileptr:
5. print("file is opened successfully")
Output:
<class '_io.TextIOWrapper'>
file is opened successfully
In the above code, we have passed filename as a first argument and opened file in
read mode as we mentioned r as the second argument. The fileptr holds the file
object and if the file is opened successfully, it will execute the print statement
Syntax
1. fileobject.close()
After closing the file, we cannot perform any operation in the file. The file needs to
be properly closed. If any exception occurs while performing some operations in the
file then the program terminates without closing the file.
1. try:
2. fileptr = open("file.txt")
3. # perform file operations
4. finally:
5. fileptr.close()
The syntax to open a file using with the statement is given below.
It is always suggestible to use the with statement in the case of files because, if the
break, return, or exception occurs in the nested block of code then it automatically
closes the file, we don't need to write the close() function. It doesn't let the file to
corrupt.
Example
1. with open("file.txt",'r') as f:
2. content = f.read();
3. print(content)
w: It will overwrite the file if any file exists. The file pointer is at the beginning of
the file.
a: It will append the existing file. The file pointer is at the end of the file. It creates a
new file if no file exists.
Example
1. # open the file.txt in append mode. Create a new file if no such file exists.
2. fileptr = open("file2.txt", "w")
3.
4. # appending the content to the file
5. fileptr.write('''''Python is the modern day language. It makes things so simple
.
6. It is the fastest-growing programing language''')
7.
8. # closing the opened the file
9. fileptr.close()
Output:
File2.txt
We have opened the file in w mode. The file1.txt file doesn't exist, it created a new
file and we have written the content in the file using the write() function.
Example 2
1. #open the file.txt in write mode.
2. fileptr = open("file2.txt","a")
3.
4. #overwriting the content of the file
5. fileptr.write(" Python has an easy syntax and user-friendly interaction.")
6.
7. #closing the opened file
8. fileptr.close()
Output:
We can see that the content of the file is modified. We have opened the file
in a mode and it appended the content in the existing file2.txt.
To read a file using the Python script, the Python provides the read() method.
The read() method reads a string from the file. It can read the data in the text as
well as a binary format.
1. fileobj.read(<count>)
Here, the count is the number of bytes to be read from the file starting from the
beginning of the file. If the count is not specified, then it may read the content of
the file until the end.
Example
1. #open the file.txt in read mode. causes error if no such file exists.
2. fileptr = open("file2.txt","r")
3. #stores all the data of the file into the variable content
4. content = fileptr.read(10)
5. # prints the type of the data stored in the file
6. print(type(content))
7. #prints the content of the file
8. print(content)
9. #closes the opened file
10.fileptr.close()
Output:
<class 'str'>
Python is
If we use the following line, then it will print all content of the file.
1. content = fileptr.read()
2. print(content)
Output:
Output:
Consider the following example which contains a function readline() that reads the
first line of our file "file2.txt" containing three lines. Consider the following
example.
Output:
We called the readline() function two times that's why it read two lines from the
file.
Python provides also the readlines() method which is used for the reading lines. It
returns the list of the lines till the end of file(EOF) is reached.
Output:
x: it creates a new file with the specified name. It causes an error a file exists with
the same name.
a: It creates a new file with the specified name if no such file exists. It appends the
content to the file if the file already exists with the specified name.
w: It creates a new file with the specified name if no such file exists. It overwrites
the existing file.
Example 1
1. #open the file.txt in read mode. causes error if no such file exists.
2. fileptr = open("file2.txt","x")
3. print(fileptr)
4. if fileptr:
5. print("File created successfully")
Output:
Output:
For this purpose, the Python provides us the seek() method which enables us to
modify the file pointer position externally.
Syntax:
1. <file-ptr>.seek(offset[, from)
offset: It refers to the new position of the file pointer within the file.
from: It indicates the reference position from where the bytes are to be moved. If it
is set to 0, the beginning of the file is used as the reference position. If it is set to 1,
the current position of the file pointer is used as the reference position. If it is set to
2, the end of the file pointer is used as the reference position.
Example
1. # open the file file2.txt in read mode
2. fileptr = open("file2.txt","r")
3.
4. #initially the filepointer is at 0
5. print("The filepointer is at byte :",fileptr.tell())
6.
7. #changing the file pointer location to 10.
8. fileptr.seek(10);
9.
10.#tell() returns the location of the fileptr.
11.print("After reading, the filepointer is at:",fileptr.tell())
Output:
Python OS module
Renaming the file
The Python os module enables interaction with the operating system. The os module
provides the functions that are involved in file processing operations like renaming,
deleting, etc. It provides us the rename() method to rename the specified file to a
new name. The syntax to use the rename() method is given below.
Syntax:
1. rename(current-name, new-name)
The first argument is the current file name and the second argument is the modified
name. We can change the file name bypassing these two arguments.
Example 1:
1. import os
2.
3. #rename file2.txt to file3.txt
4. os.rename("file2.txt","file3.txt")
Output:
1. remove(file-name)
Example 1
1. import os;
2. #deleting the file named file3.txt
3. os.remove("file3.txt")
Syntax:
1. mkdir(directory name)
Example 1
1. import os
2.
3. #creating a new directory with the name new
4. os.mkdir("new")
Syntax
1. os.getcwd()
Example
1. import os
2. os.getcwd()
Output:
'C:\\Users\\DEVANSH SHARMA'
Syntax
1. chdir("new-directory")
Example
1. import os
2. # Changing current directory with the new directiory
3. os.chdir("C:\\Users\\DEVANSH SHARMA\\Documents")
4. #It will display the current working directory
5. os.getcwd()
Output:
'C:\\Users\\DEVANSH SHARMA\\Documents'
Deleting directory
The rmdir() method is used to delete the specified directory.
Syntax
1. os.rmdir(directory name)
Example 1
1. import os
2. #removing the new directory
3. os.rmdir("directory_name")
The following example contains two python scripts. The script file1.py executes the
script file.py and writes its output to the text file output.txt.
Example
file.py
1. temperatures=[10,-20,-289,100]
2. def c_to_f(c):
3. if c< -273.15:
4. return "That temperature doesn't make sense!"
5. else:
6. f=c*9/5+32
7. return f
8. for t in temperatures:
9. print(c_to_f(t))
file.py
1. import subprocess
2.
3. with open("output.txt", "wb") as f:
4. subprocess.check_call(["python", "file.py"], stdout=f)
SN Method Description
1 file.close() It closes the opened file. The file once
closed, it can't be read or write anymore.
In Python, the date is not a data type, but we can work with the date objects by
importing the module named with datetime, time, and calendar.
o date - It is a naive ideal date. It consists of the year, month, and day as
attributes.
o time - It is a perfect time, assuming every day has precisely 24*60*60
seconds. It has hour, minute, second, microsecond, and tzinfo as attributes.
o datetime - It is a grouping of date and time, along with the attributes year,
month, day, hour, minute, second, microsecond, and tzinfo.
o timedelta - It represents the difference between two dates, time or datetime
instances to microsecond resolution.
o tzinfo - It provides time zone information objects.
Example
Create a date object:
import datetime
x = datetime.datetime(2020, 5, 17)
print(x)
The datetime() class also takes parameters for time and timezone (hour,
minute, second, microsecond, tzone), but they are optional, and has a
default value of 0, (None for timezone).
import datetime
datetime_object = datetime.datetime.now()
print(datetime_object)
When you run the program, the output will be something like:
2018-12-19 09:26:03.478039
Time tuple
The time is treated as the tuple of 9 numbers. Let's look at the members of the time
tuple.
1 Month 1 to 12
2 Day 1 to 31
3 Hour 0 to 23
4 Minute 0 to 59
5 Second 0 to 60
6 Day of weak 0 to 6
Example
1. import time
2. #returns the formatted time
3.
4. print(time.asctime(time.localtime(time.time())))
Output:
Example
1. import time
2. for i in range(0,5):
3. print(i)
4. #Each element will be printed after 1 second
5. time.sleep(1)
To work with dates as date objects, we have to import the datetime module into
the python source code.
Consider the following example to get the datetime object representation for the
current time.
Example
1. import datetime
2. #returns the current datetime object
3. print(datetime.datetime.now())
Consider the following example to print the calendar for the last month of 2018.
Example
1. import calendar;
2. cal = calendar.month(2020,3)
3. #printing the calendar of December 2018
4. print(cal)
1. import calendar
2. #printing the calendar of the year 2019
3. s = calendar.prcal(2020)
timestamp = 1545730073
dt_object = datetime.fromtimestamp(timestamp)
Python strftime()
In this article, you will learn to convert date, time and datetime objects to its
equivalent string (with the help of examples)
year = now.strftime("%Y")
print("year:", year)
month = now.strftime("%m")
print("month:", month)
day = now.strftime("%d")
print("day:", day)
time = now.strftime("%H:%M:%S")
print("time:", time)
When you run the program, the output will something like be:
year: 2018
month: 12
day: 24
time: 04:59:31
date and time: 12/24/2018, 04:59:31
Here, year , day , time and date_time are strings, whereas now is
a datetime object.
4. The string you pass to the strftime() method may contain more than
one format codes.
import time
while True:
localtime = time.localtime()
result = time.strftime("%I:%M:%S %p", localtime)
print(result)
time.sleep(1)
In the above program, we computed and printed the current local time
inside the infinite while loop. Then, the program waits for 1 second. Again,
the current local time is computed and printed. This process goes on.
When you run the program, the output will be something like:
02:10:50 PM
02:10:51 PM
02:10:52 PM
02:10:53 PM
02:10:54 PM
... .. ...
while True:
localtime = time.localtime()
result = time.strftime("%I:%M:%S %p", localtime)
print(result, end="", flush=True)
print("\r", end="", flush=True)
time.sleep(1)
today = date.today()
print("Today's date:", today)
Here, we imported the date class from the datetime module. Then, we used
the date.today() method to get the current local date.
By the way, date.today() returns a date object, which is assigned to
the today variable in the above program. Now, you can use
the strftime() method to create a string representing date in different
formats.
today = date.today()
# dd/mm/YY
d1 = today.strftime("%d/%m/%Y")
print("d1 =", d1)
# mm/dd/y
d3 = today.strftime("%m/%d/%y")
print("d3 =", d3)
When you run the program, the output will be something like:
d1 = 16/09/2019
d2 = September 16, 2019
d3 = 09/16/19
d4 = Sep-16-2019
If you need to get the current date and time, you can use datetime class of
the datetime module.
# dd/mm/YY H:M:S
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
print("date and time =", dt_string)
Here, we have used datetime.now() to get the current date and time. Then,
we used strftime() to create a string representing date and time in another
format.