In this article, we are discussing Arrays in Python. The Array is used in every programming language, like C, C++, Java, Python, R, JavaScript, etc. By using an array, we can store more than one data. The Array is a process of memory allocation. It is performed as a dynamic memory allocation. We can declare an array like x[100], storing 100 data in x. It is a container that can hold a fixed number of items, and these items should be the same type. An array is popular in most programming languages like C/C++, JavaScript, etc.
The Array is an idea of storing multiple items of the same type together, making it easier to calculate the position of each element by simply adding an offset to the base value. A combination of the arrays could save a lot of time by reducing the overall size of the code. It is used to store multiple values in a single variable. If you have a list of items that are stored in their corresponding variables like this:
If you want to loop through cars and find a specific one, you can use the Array. You can use an array to store more than one item in a specific variable.
The Array can be handled in Python by a module named Array. It is useful when we must manipulate only specific data values. The following are the terms to understand the concept of an array:
Element – Each item stored in an array is called an element.
Index – The location of an element in an array has a numerical index, which is used to identify the element’s position. The index value is very much important in an Array.
Array Representation:
An array can be declared in various ways and in different languages. The important points that should be considered are as follows:
The index starts with 0.
We can easily find any elements within this Array using the Index value.
The length of the Array defines the capacity to store the elements. It is written like x[100], which means the length of array x is specified by 100.
Array operations
Some of the basic operations supported by an array are as follows:
Traverse – It prints all the elements one by one.
Insertion – It adds an element at the given index.
Deletion – It deletes an element at the given index.
Search – It searches an element using the given index or by the value.
Update – It updates an element at the given index.
The Array can be created in Python by importing the array module to the python program.
from array import *
arrayName = array(typecode, [initializers])
Accessing array elements
We can access the array elements using the respective indices of those elements.
Program code:
Here we give an example of how we access the elements of an array using its index value in Python. The code is given below –
import array as arr
a = arr.array('i', [2, 4, 5, 6])
print("First element is:", a[0])
print("Second element is:", a[1])
print("Third element is:", a[2])
print("Forth element is:", a[3])
print("last element is:", a[-1])
print("Second last element is:", a[-2])
print("Third last element is:", a[-3])
print("Forth last element is:", a[-4])
print(a[0], a[1], a[2], a[3], a[-1],a[-2],a[-3],a[-4])
Output:
Now we compile the above code in python, and after successful compilation, we run it. Then the output is given below -First element is: 2 Second element is: 4 Third element is: 5 Forth element is: 6 last element is: 6 Second last element is: 5 Third last element is: 4 Forth last element is: 2 2 4 5 6 6 5 4 2
Explanation:
In the above example, we have imported an array, defined a variable named “a” that holds the elements of an array, and printed the elements by accessing elements through the indices of an array. Here we can easily find out the array element by using the array index like a[0], a[1], a[-1], and so on.
How to change or add elements?
Arrays are mutable, and their elements can be changed similarly to lists.
Program code:
Here in this example, we can change or add or replace any element from the Array in Python. The code is given below –
import array as arr
numbers = arr.array('i', [1, 2, 3, 5, 7, 10])
# changing first element 1 by the value 0.
numbers[0] = 0
print(numbers) # Output: array('i', [0, 2, 3, 5, 7, 10])
# changing last element 10 by the value 8.
numbers[5] = 8
print(numbers) # Output: array('i', [0, 2, 3, 5, 7, 10])
# replace the value of 3rd to 5th element by 4, 6 and 8
numbers[2:5] = arr.array('i', [4, 6, 8])
print(numbers) # Output: array('i', [0, 2, 4, 6, 8, 10])
Output:
Now we compile the above code in python, and after successful compilation, we run it. Then the output is given below -array(‘i’, [0, 2, 3, 5, 7, 10]) array(‘i’, [0, 2, 3, 5, 7, 8]) array(‘i’, [0, 2, 4, 6, 8, 8])
Explanation:
In the above example, we have imported an array and defined a variable named “numbers,” which holds the value of an array. If we want to change or add the elements in an array, we can do it by defining the index of an array where we want to change or add the elements. Here we just mentioned the index number of elements you want to change and declared the new value by which you want to replace the old elements.
Why use Arrays in Python?
A combination of arrays saves a lot of time. The Array can reduce the overall size of the code. Using an array, we can solve a problem quickly in any language. The Array is used for dynamic memory allocation.
How to Delete Elements from an Array?
The elements can be deleted from an array using Python’s del statement. If we want to delete any value from the Array, we can use the indices of a particular element.
import array as arr
number = arr.array('i', [1, 2, 3, 3, 4])
del number[2] # removing third element
print(number) # Output: array('i', [1, 2, 3, 4])
Output:
Now we compile the above code in python, and after successful compilation, we run it. Then the output is given below -array(‘i’, [10, 20, 40, 60])
Explanation: In the above example, we have imported an array and defined a variable named as “number” which stores the values of an array. Here, by using del statement, we are removing the third element [3] of the given array.
Finding the length of an array
The length of an array is defined as the number of elements present in an array. It returns an integer value that is equal to the total number of the elements present in that array.
Syntax
len(array_name)
Array Concatenation
We can easily concatenate any two arrays using the + symbol.
Now we compile the above code in python, and after successful compilation, we run it. Then the output is given below -Array c= array(‘d’, [1.1, 2.1, 3.1, 2.6, 7.8, 3.7, 8.6])
Explanation
In the above example, we have defined variables named as “a, b, c” that hold the values of an array.
import array as arr
x = arr.array('i', [4, 7, 19, 22]) # Initialize the array elements
print("First element:", x[0])
print("Second element:", x[1])
print("Second last element:", x[-1])
Output:First element: 4 Second element: 7 Second last element: 22
Now we compile the above code in python, and after successful compilation, we run it. Then the output is given below –
Explanation:
In the above example, first, we imported an array and defined a variable named “x,” which holds the value of an array. Then, we printed the elements of an array using the index value of this array element.
The term “IDE” refers for “Integrated Development Environment,” which is a coding tool that aids in automating the editing, compiling, testing, and other steps of an SDLC while making it simple for developers to execute, write, and debug code.
It is specifically made for software development and includes a number of tools that are used in the creation and testing of the software.
There are some Python IDEs which are as follows:
PyCharm
Spyder
PyDev
Atom
Wing
Jupyter Notebook
Thonny
Rodeo
Microsoft Visual Studio
Eric
PyCharm
The Jet Brains created PyCharm, a cross-platform Integrated Development Environment (IDE) created specifically for Python. It is the most popular IDE and is accessible in both a premium and a free open-source version. By handling everyday duties, a lot of time is saved.
It is a full-featured Python IDE with a wealth of features including auto code completion, easy project navigation, quick error checking and correction, support for remote development, database accessibility, etc.
Features
Smart code navigation
Errors Highlighting
Powerful debugger
Supports Python web development frameworks, i.e., Angular JS, Javascript
Spyder
Spyder is a well-known open-source IDE that is best suited for data research and has a high level of recognition in the industry. Scientific Python Development Environment is Spyder’s full name. It supports all popular operating systems, including Windows, MacOS X, and Linux.
A number of features are offered by it, including a localised code editor, a document viewer, a variable explorer, an integrated console, etc. It also supports a number of scientific modules, including SciPy and NumPy.
Features
Proper syntax highlighting and auto code completion
Integrates strongly with IPython console
Performs well in multi-language editor and auto code completion mode
PyDev
As an external plugin for Eclipse, PyDev is one of the most popular Python IDEs. The Python programmers who have a background in Java naturally gravitate towards this Python interpreter because it is so well-liked by users.
In 2003-2004, Aleksandar Totic, who is well known for his work on the Mosaic browser, contributed to the Pydev project.
Django integration, code auto-completion, smart and block indents, among other features, are features of Pydev.
Features
Strong Parameters like refactoring, debugging, code analysis, and code coverage function.
It supports virtual environments, Mypy, and black formatter.
Also supports PyLint integration, remote debugger, Unit test integration, etc.
Atom
GitHub, a company that was first founded as an open-source, cross-platform project, is the company that creates Atom. It is built on the Electron framework, which enables cross-platform desktop applications utilising Chromium and Node.js and is dubbed the “Hackable Text Editor for the 21st Century.”
Features
Visualize the results on Atom without open any other window.
A plugin named “Markdown Preview Plus” provides built-in support for editing and visualizing Markdown files.
Wing
It’s described as a cross-platform IDE with a tonne of useful features and respectable development support. It is free to use in its personal edition. The 30-day trial period for the pro version is provided for the benefit of the developers.
Features
Customizable and can have extensions as well.
Supports remote development, test-driven development along with the unit test.
Jupyter Notebook
Jupyter is one of the most used Python notebook editors that is used across the Data Science industry. You can create and edit notebook documents using this web application, which is based on the server-client architecture. It utilises Python’s interpretive nature to its fullest potential.
Features
Supports markdowns
Easy creation and editing of codes
Ideal for beginners in data science
Thonny
Thonny is a Python IDE (Integrated Development Environment) that is open-source, free, and geared towards beginners. Since its initial release in 2016, it has grown to be a well-liked option for novice Python coders.
Thonny’s user-friendly interface is one of its most distinguishing qualities. It makes it simple for beginners to learn Python and debug their programmes because it incorporates a code editor, debugger, and REPL (Read-Eval-Print-Loop) in a single window. To assist users with writing proper code, Thonny also has tools like code completion, syntax highlighting, and error highlighting.
Thonny IDE that works well for teaching and learning programming is Thonny. Software that highlights syntax problems and aids code completion was created at the University of Tartu.
Features
Simple debugger
Supports highlighting errors and auto code completion
Rodeo
When it comes to gathering data and information from many sources for data science projects, Rodeo is considered one of the top Python IDEs.
It offers code auto-completion and cross-platform capability.
Features
Allows the functions for comparing data, interact, plot, and inspect data.
Auto code completion, syntax highlighter, visual file navigator, etc.
Microsoft Visual Studio
Microsoft Visual Studio is an open-source code editor which was best suited for development and debugging of latest web and cloud projects. It has its own marketplace for extensions.
An integrated development environment (IDE) called Microsoft Visual Studio is used to create software for the Windows, Android, and iOS operating systems. Since its initial release in 1997, it has grown to be a well-liked software development tool.
Code editing, debugging, and code analysis are just a few of the capabilities and tools that are included in the IDE. It supports a variety of programming languages, including Python, C++, C#, Visual Basic, and others. Additionally, Microsoft Visual Studio comes with a variety of project templates that make it simpler for developers to get started on their projects right away.
Microsoft Visual Studio 2022, the most recent release, comes with new features like improved debugging and testing capabilities, improved Git integration, and a revamped user interface. The enhanced performance of the IDE makes it quicker and more effective to construct complicated software projects.
Features
Supports Python Coding in Visual studio
Available in both paid and free version
Eric Python
The Eric Python is a Python-based editor that may be used for both professional and non-professional tasks.
Since its initial release in 2000, Eric IDE (Integrated Development Environment) has been a free and open-source Python IDE. It offers programmers a setting in which to efficiently write, test, and debug Python programmes since it is user-friendly and simple to use.
Python 2 and 3 are among the Python versions that are supported by Eric IDE, which also offers features like code highlighting, code completion, and syntax checking. Additionally, it contains an integrated debugger that enables programmers to effectively debug their programmes.
The Eric IDE’s plugin system, which enables developers to increase its capabilities, is one of its primary features. An integrated version control system, a database browser, and a Python profiler are just a few of the plugins that are available for the Eric IDE.
The Python collection module is defined as a container that is used to store collections of data, for example – list, dict, set, and tuple, etc. It was introduced to improve the functionalities of the built-in collection containers.
Python collection module was first introduced in its 2.4 release.
There are different types of collection modules which are as follows:
namedtuple()
The Python namedtuple() function returns a tuple-like object with names for each position in the tuple. It was used to eliminate the problem of remembering the index of each field of a tuple object in ordinary tuples.
Examples
pranshu = ('James', 24, 'M')
print(pranshu)
Output:(‘James’, 24, ‘M’)
OrderedDict()
The Python OrderedDict() is similar to a dictionary object where keys maintain the order of insertion. If we try to insert key again, the previous value will be overwritten for that key.
Example
import collections
d1=collections.OrderedDict()
d1['A']=10
d1['C']=12
d1['B']=11
d1['D']=13
for k,v in d1.items():
print (k,v)
Output:A 10 C 12 B 11 D 13
defaultdict()
The Python defaultdict() is defined as a dictionary-like object. It is a subclass of the built-in dict class. It provides all methods provided by dictionary but takes the first argument as a default data type.
Example
from collections import defaultdict
number = defaultdict(int)
number['one'] = 1
number['two'] = 2
print(number['three'])
Output:0
Counter()
The Python Counter is a subclass of dictionary object which helps to count hashable objects.
Example
from collections import Counter
c = Counter()
list = [1,2,3,4,5,7,8,5,9,6,10]
Counter(list)
Counter({1:5,2:4})
list = [1,2,4,7,5,1,6,7,6,9,1]
c = Counter(list)
print(c[1])
Output:3
deque()
The Python deque() is a double-ended queue which allows us to add and remove elements from both the ends.
Example
from collections import deque
list = ["x","y","z"]
deq = deque(list)
print(deq)
Output:deque([‘x’, ‘y’, ‘z’])
Chainmap Objects
A chainmap class is used to groups multiple dictionary together to create a single list. The linked dictionary stores in the list and it is public and can be accessed by the map attribute. Consider the following example.
The UserDict behaves as a wrapper around the dictionary objects. The dictionary can be accessed as an attribute by using the UserDict object. It provides the easiness to work with the dictionary.
It provides the following attribute.
data – A real dictionary used to store the contents of the UserDict class.
UserList Objects
The UserList behaves as a wrapper class around the list-objects. It is useful when we want to add new functionality to the lists. It provides the easiness to work with the dictionary.
It provides the following attribute.
data – A real list is used to store the contents of the User class.
UserString Objects
The UserList behaves as a wrapper class around the list objects. The dictionary can be accessed as an attribute by using the UserString object. It provides the easiness to work with the dictionary.
It provides the following attribute.
data – A real str object is used to store the contents of the UserString class.
In this tutorial, we are discussing list comprehension in Python. Python is known for helping us produce code that is elegant, simple to write, and reads almost as well as plain English. List comprehension is one of the language’s most distinguishing features, allowing us to develop sophisticated functionality with just one line of code. On the other hand, many Python writers struggle to fully utilize the more complex aspects of list comprehension. Sometimes programmers may overuse them, resulting in much less efficient and difficult-to-read code.
Example:
Here we give the basic example of List comprehension in Python. The code is given below –
Person = ["Piyali", "Hiya", "Rudrashish", "Badsha", "Lipi"]
newlist = [x for x in Person if "i" in x]
print(newlist)
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -[‘Piyali’, ‘Hiya’, ‘Rudrashish’, ‘Lipi’]
Syntax:
The syntax of List comprehension in Python is given below –
newlist = [expression for item in iterable if condition == True]
Here we are showing the basic use of list comprehension.
Program Code:
Now we give code examples without using list comprehension; how can we square every number of a list using just a for loop in Python? The code is given below –
#using for loop to iterate through items in list
numbers = [3, 5, 1, 7, 3, 9]
num = []
for n in numbers:
num.append(n**2)
print(num)
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -[9, 25, 1, 49, 9, 81]
This can be accomplished with only a single line of code using list comprehension.
Program Code:
Now we give code examples of list comprehension in Python for square every number of a list. The code is given below –
#using list comprehension to iterate through list items
numbers = [3, 5, 1, 7, 3, 9]
num = [n**2 for n in numbers]
print(num)
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below –
Benefits of Using List Comprehensions
There are so many advantages or benefits of using list comprehension in Python. The advantages are given below –
1. Loops and maps:
Loops and maps are typically regarded as more Pythonic than list comprehensions. But rather than taking that judgment at face value, it is worth considering the advantages of utilizing a list comprehension in Python over the alternatives. We will learn about a couple of cases when the alternatives are preferable options later.
2. The Single tool uses:
One of the essential advantages of utilizing list comprehension in Python is that it is a single tool that can be used in various circumstances. We don’t need to adopt a new strategy for each situation. List comprehensions may be leveraged for mapping or filtering and basic list generation.
3. Does not depend on appropriate parameter:
List comprehensions are regarded as Pythonic, as Python emphasizes simple, effective tools that can be used in many scenarios. As a bonus, we won’t have to remember the appropriate order of parameters when using a list comprehension in Python, as we would when calling map().
4. Easy to use:
List comprehensions are easier to read and grasp than loops since they are more declarative. We must concentrate on how exactly the List is constructed while using loops. We must manually build an empty list, loop over the List’s entries, and add each one to the List’s end. Instead, using a list comprehension in Python, we can concentrate on what we want to put in the List and allow Python to handle the list generation.
Program Code:
# Import module to keep track of time
import time
# defining function to execute for loop
def for_loop(num):
l = []
for i in range(num):
l.append(i + 10)
return l
# defining function to execute list comprehension
def list_comprehension(num):
return [i + 10 for i in range(num)]
# Giving values to the functions
# Calculating time taken by for loop
start = time.time()
for_loop(10000000)
end = time.time()
print('Time taken by for loop:', (end - start))
# Calculating time taken by list comprehension
start = time.time()
list_comprehension(10000000)
end = time.time()
print('Time taken by list comprehension:', (end - start))
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -Time taken by for loop: 7.005999803543091 Time taken by list comprehension: 2.822999954223633
Using List Comprehension to Iterate through String
List comprehension can also be used in the case of strings, as they are iterables.
Program Code:
Now we give code examples of using list comprehension in Python to iterate a string given in code. The code is given below –
letters = [ alpha for alpha in 'javatpoint' ]
print( letters)
Conditional statements can be used by list comprehensions to change existing lists (or other tuples). We’ll make a list with mathematical operators, numbers, and a range of values.
Program Code:
number_list = [ num for num in range(30) if num % 2 != 0]
print(number_list)
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29]
Addition of odd elements to the List:
Here we sum the odd elements from the given List. It is an example of list comprehension in Python. The code is given below –
def Sum(n):
dsum = 0
for ele in str(n):
dsum += int(ele)
return dsum
List = [47, 69, 73, 97, 105, 845, 307]
newList = [Sum(i) for i in List if i & 1]
print(newList)
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -[11, 15, 10, 16, 6, 17, 10]
Nested List Comprehensions
Nested List Comprehensions are similar to nested for loops in that they are a list comprehension inside another list comprehension. The programme that implements nested loop is as follows:
Program Code:
nested_list = []
for _ in range(3):
# Append an empty sublist inside the list
nested_list.append([])
for __ in range(5):
nested_list[_].append(__ + _)
print(nested_list)
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -[[0, 1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 3, 4, 5, 6]]
The same result may be created in fewer lines of code by utilizing layered list comprehensions.
Program Code:
The code for nested list comprehension is given below –
# Nested list comprehension
nested_list = [[_ + __ for _ in range(5)] for __ in range(3)]
print(nested_list)
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -[[0, 1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 3, 4, 5, 6]]
List comprehension is a powerful tool for describing and creating new lists based on existing ones. In general, list comprehension is lighter and easier to use than traditional list construction functions and loops. To provide user-friendly code, we should avoid writing large codes for list comprehensions. Every interpretation of the list or other iterables can be recast in a for loop, but not all the for loops can be rebuilt in the framework of list comprehension.
Python assert keyword is defined as a debugging tool that tests a condition. The Assertions are mainly the assumption that asserts or state a fact confidently in the program. For example, while writing a division function, the divisor should not be zero, and you assert that the divisor is not equal to zero.
It is merely a Boolean expression that has a condition or expression checks if the condition returns true or false. If it is true, the program does not do anything, and it moves to the next line of code. But if it is false, it raises an AssertionError exception with an optional error message.
The main task of assertions is to inform the developers about unrecoverable errors in the program like “file not found”, and it is right to say that assertions are internal self-checks for the program. It is the most essential for the testing or quality assurance in any application development area. The syntax of the assert keyword is given below.
Syntax
assert condition, error_message(optional)
Why Assertion is used
It is a debugging tool, and its primary task is to check the condition. If it finds that the condition is true, it moves to the next line of code, and If not, then stops all its operations and throws an error. It points out the error in the code.
Where Assertion in Python used
Checking the outputs of the functions.
Used for testing the code.
In checking the values of arguments.Checking the valid input.
Example1
This example shows the working of assert with the error message.
def avg(scores):
assert len(scores) != 0,"The List is empty."
return sum(scores)/len(scores)
scores2 = [67,59,86,75,92]
print("The Average of scores2:",avg(scores2))
scores1 = []
print("The Average of scores1:",avg(scores1))
Output:The Average of scores2: 75.8 AssertionError: The List is empty.
Explanation: In the above example, we have passed a non-empty list scores2 and an empty list scores1 to the avg() function. We received an output for scores2 list successfully, but after that, we got an error AssertionError: List is empty. The assert condition is satisfied by the scores2 list and lets the program continue to run. However, scores1 doesn’t satisfy the condition and gives an AssertionError.
Example2:
This example shows the “Divide by 0 error” in the console.
# initializing number
x = 7
y = 0
# It uses assert to check for 0
print ("x / y value is : ")
assert y != 0, "Divide by 0 error"
print (x / y)
Output:
x / y value is :
Runtime Exception :
Traceback (most recent call last): File “main.py”, line 6, in <module> assert y != 0, “Divide by 0 error” AssertionError: Divide by 0 error
Explanation:
In the above example, we have initialized an integer variable, i.e., x=7, y=0, and try to print the value of x/y as an output. The Python interpreter generated a Runtime Exception because of the assert keyword found the divisor as zero then displayed “Divide by 0 error” in the console.
Simple Mail Transfer Protocol (SMTP) is used as a protocol to handle the email transfer using Python. It is used to route emails between email servers. It is an application layer protocol which allows to users to send mail to another. The receiver retrieves email using the protocols POP(Post Office Protocol) and IMAP(Internet Message Access Protocol).
When the server listens for the TCP connection from a client, it initiates a connection on port 587.
Python provides a smtplib module, which defines an the SMTP client session object used to send emails to an internet machine. For this purpose, we have to import the smtplib module using the import statement.
$ import smtplib
The SMTP object is used for the email transfer. The following syntax is used to create the smtplib object.
host: It is the hostname of the machine which is running your SMTP server. Here, we can specify the IP address of the server like (https://www. smartstart.com) or localhost. It is an optional parameter.
port: It is the port number on which the host machine is listening to the SMTP connections. It is 25 by default.
local_hostname: If the SMTP server is running on your local machine, we can mention the hostname of the local machine.
The sendmail() method of the SMTP object is used to send the mail to the desired machine. The syntax is given below.
smtpObj.sendmail(sender, receiver, message)
Example
#!/usr/bin/python3
import smtplib
sender_mail = '[email protected]'
receivers_mail = ['[email protected]']
message = """From: From Person %s
To: To Person %s
Subject: Sending SMTP e-mail
This is a test e-mail message.
"""%(sender_mail,receivers_mail)
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender_mail, receivers_mail, message)
print("Successfully sent email")
except Exception:
print("Error: unable to send email")
Sending email from gmail
There are cases where the emails are sent using the Gmail SMTP server. In this case, we can pass Gmail as the SMTP server instead of using the localhost with the port 587.
Use the following syntax.
$ smtpObj = smtplib.SMTP(“gmail.com”, 587)
Here, we need to login to the Gmail account using Gmail user name and password. For this purpose, the smtplib provide the login() method, which accepts the username and password of the sender.
This may make your Gmail ask you for access to less secure apps if you’re using Gmail. You will need to turn this ON temporarily for this to work.
Python provides the datetime module work with real dates and times. In real-world applications, we need to work with the date and time. Python enables us to schedule our Python script to run at a particular timing.
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.
In this section of the tutorial, we will discuss how to work with the date and time objects in Python.
The datetime classes are classified in the six main classes.
date – It is a naive ideal date. It consists of the year, month, and day as attributes.
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.
datetime – It is a grouping of date and time, along with the attributes year, month, day, hour, minute, second, microsecond, and tzinfo.
timedelta – It represents the difference between two dates, time or datetime instances to microsecond resolution.
tzinfo – It provides time zone information objects.
timezone – It is included in the new version of Python. It is the class that implements the tzinfo abstract base class.
Tick
In Python, the time instants are counted since 12 AM, 1st January 1970. The function time() of the module time returns the total number of ticks spent since 12 AM, 1st January 1970. A tick can be seen as the smallest unit to measure the time.
Consider the following example
import time;
#prints the number of ticks spent since 12 AM, 1st January 1970
print(time.time())
Output:1585928913.6519969
How to get the current time?
The localtime() functions of the time module are used to get the current time tuple. Consider the following example.
Example
import time;
#returns a time tuple
print(time.localtime(time.time()))
The time is treated as the tuple of 9 numbers. Let’s look at the members of the time tuple.
Index
Attribute
Values
0
Year
4 digit (for example 2018)
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
7
Day of year
1 to 366
8
Daylight savings
-1, 0, 1 , or -1
Getting formatted time
The time can be formatted by using the asctime() function of the time module. It returns the formatted time for the time tuple being passed.
Example
import time
#returns the formatted time
print(time.asctime(time.localtime(time.time())))
Output:Tue Dec 18 15:31:39 2018
Python sleep time
The sleep() method of time module is used to stop the execution of the script for a given amount of time. The output will be delayed for the number of seconds provided as the float.
Consider the following example.
Example
import time
for i in range(0,5):
print(i)
#Each element will be printed after 1 second
time.sleep(1)
Output:0 1 2 3 4
The datetime Module
The datetime module enables us to create the custom date objects, perform various operations on dates like the comparison, etc.
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
import datetime
#returns the current datetime object
print(datetime.datetime.now())
Output:2020-04-04 13:18:35.252578
Creating date objects
We can create the date objects bypassing the desired date in the datetime constructor for which the date objects are to be created.
Consider the following example.
Example
import datetime
#returns the datetime object for the specified date
print(datetime.datetime(2020,04,04))
Output:2020-04-04 00:00:00
We can also specify the time along with the date to create the datetime object. Consider the following example.
Example
import datetime
#returns the datetime object for the specified time
print(datetime.datetime(2020,4,4,1,26,40))
Output:2020-04-04 01:26:40
In the above code, we have passed in datetime() function year, month, day, hour, minute, and millisecond attributes in a sequential manner.
Comparison of two dates
We can compare two dates by using the comparison operators like >, >=, <, and <=.
Consider the following example.
Example
from datetime import datetime as dt
#Compares the time. If the time is in between 8AM and 4PM, then it prints working hours otherwise it prints fun hours
if dt(dt.now().year,dt.now().month,dt.now().day,8)<dt.now()<dt(dt.now().year,dt.now().month,dt.now().day,16):
print("Working hours....")
else:
print("fun hours")
Output:fun hours
The calendar module
Python provides a calendar object that contains various methods to work with the calendars.
Consider the following example to print the calendar for the last month of 2018.
Example
import calendar;
cal = calendar.month(2020,3)
#printing the calendar of December 2018
print(cal)
Output:March 2020 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Printing the calendar of whole year
The prcal() method of calendar module is used to print the calendar of the entire year. The year of which the calendar is to be printed must be passed into this method.
Example
import calendar
#printing the calendar of the year 2019
s = calendar.prcal(2020)
When a Python program meets an error, it stops the execution of the rest of the program. An error in Python might be either an error in the syntax of an expression or a Python exception. We will see what an exception is. Also, we will see the difference between a syntax error and an exception in this tutorial. Following that, we will learn about trying and except blocks and how to raise exceptions and make assertions. After that, we will see the Python exceptions list.
What is an Exception?
An exception in Python is an incident that happens while executing a program that causes the regular course of the program’s commands to be disrupted. When a Python code comes across a condition it can’t handle, it raises an exception. An object in Python that describes an error is called an exception.
When a Python code throws an exception, it has two options: handle the exception immediately or stop and quit.
Exceptions versus Syntax Errors
When the interpreter identifies a statement that has an error, syntax errors occur. Consider the following scenario:
Code
#Python code after removing the syntax error
string = "Python Exceptions"
for s in string:
if (s != o:
print( s )
Output: if (s != o: ^ SyntaxError: invalid syntax
The arrow in the output shows where the interpreter encountered a syntactic error. There was one unclosed bracket in this case. Close it and rerun the program:
Code
#Python code after removing the syntax error
string = "Python Exceptions"
for s in string:
if (s != o):
print( s )
Output: 2 string = “Python Exceptions” 4 for s in string: —-> 5 if (s != o): 6 print( s ) NameError: name ‘o’ is not defined
We encountered an exception error after executing this code. When syntactically valid Python code produces an error, this is the kind of error that arises. The output’s last line specified the name of the exception error code encountered. Instead of displaying just “exception error”, Python displays information about the sort of exception error that occurred. It was a NameError in this situation. Python includes several built-in exceptions. However, Python offers the facility to construct custom exceptions.
Try and Except Statement – Catching Exceptions
In Python, we catch exceptions and handle them using try and except code blocks. The try clause contains the code that can raise an exception, while the except clause contains the code lines that handle the exception. Let’s see if we can access the index from the array, which is more than the array’s length, and handle the resulting exception.
Code
# Python code to catch an exception and handle it using try and except code blocks
a = ["Python", "Exceptions", "try and except"]
try:
#looping through the elements of the array a, choosing a range that goes beyond the length of the array
for i in range( 4 ):
print( "The index and element from the array is", i, a[i] )
#if an error occurs in the try block, then except block will be executed by the Python interpreter
except:
print ("Index out of range")
Output:The index and element from the array is 0 Python The index and element from the array is 1 Exceptions The index and element from the array is 2 try and except Index out of range
The code blocks that potentially produce an error are inserted inside the try clause in the preceding example. The value of i greater than 2 attempts to access the list’s item beyond its length, which is not present, resulting in an exception. The except clause then catches this exception and executes code without stopping it.
How to Raise an Exception
If a condition does not meet our criteria but is correct according to the Python interpreter, we can intentionally raise an exception using the raise keyword. We can use a customized exception in conjunction with the statement.
If we wish to use raise to generate an exception when a given condition happens, we may do so as follows:
Code
#Python code to show how to raise an exception in Python
num = [3, 4, 5, 7]
if len(num) > 3:
raise Exception( f"Length of the given list must be less than or equal to 3 but is {len(num)}" )
Output: 1 num = [3, 4, 5, 7] 2 if len(num) > 3: —-> 3 raise Exception( f”Length of the given list must be less than or equal to 3 but is {len(num)}” ) Exception: Length of the given list must be less than or equal to 3 but is 4
The implementation stops and shows our exception in the output, providing indications as to what went incorrect.
Assertions in Python
When we’re finished verifying the program, an assertion is a consistency test that we can switch on or off.
The simplest way to understand an assertion is to compare it with an if-then condition. An exception is thrown if the outcome is false when an expression is evaluated.
Assertions are made via the assert statement, which was added in Python 1.5 as the latest keyword.
Assertions are commonly used at the beginning of a function to inspect for valid input and at the end of calling the function to inspect for valid output.
The assert Statement
Python examines the adjacent expression, preferably true when it finds an assert statement. Python throws an AssertionError exception if the result of the expression is false.
The syntax for the assert clause is −
assert Expressions[, Argument]
Python uses ArgumentException, if the assertion fails, as the argument for the AssertionError. We can use the try-except clause to catch and handle AssertionError exceptions, but if they aren’t, the program will stop, and the Python interpreter will generate a traceback.
Code
#Python program to show how to use assert keyword
# defining a function
def square_root( Number ):
assert ( Number < 0), "Give a positive integer"
return Number**(1/2)
#Calling function and passing the values
print( square_root( 36 ) )
print( square_root( -36 ) )
Output: 7 #Calling function and passing the values —-> 8 print( square_root( 36 ) ) 9 print( square_root( -36 ) ) Input In [23], in square_root(Number) 3 def square_root( Number ): —-> 4 assert ( Number < 0), “Give a positive integer” 5 return Number**(1/2) AssertionError: Give a positive integer
Try with Else Clause
Python also supports the else clause, which should come after every except clause, in the try, and except blocks. Only when the try clause fails to throw an exception the Python interpreter goes on to the else block.
Here is an instance of a try clause with an else clause.
Code
# Python program to show how to use else clause with try and except clauses
# Defining a function which returns reciprocal of a number
def reciprocal( num1 ):
try:
reci = 1 / num1
except ZeroDivisionError:
print( "We cannot divide by zero" )
else:
print ( reci )
# Calling the function and passing values
reciprocal( 4 )
reciprocal( 0 )
Output:0.25 We cannot divide by zero
Finally Keyword in Python
The finally keyword is available in Python, and it is always used after the try-except block. The finally code block is always executed after the try block has terminated normally or after the try block has terminated for some other reason.
Here is an example of finally keyword with try-except clauses:
Code
# Python code to show the use of finally clause
# Raising an exception in try block
try:
div = 4 // 0
print( div )
# this block will handle the exception raised
except ZeroDivisionError:
print( "Atepting to divide by zero" )
# this will always be executed no matter exception is raised or not
finally:
print( 'This is code of finally clause' )
Output:Atepting to divide by zero This is code of finally clause
User-Defined Exceptions
By inheriting classes from the typical built-in exceptions, Python also lets us design our customized exceptions.
Here is an illustration of a RuntimeError. In this case, a class that derives from RuntimeError is produced. Once an exception is detected, we can use this to display additional detailed information.
We raise a user-defined exception in the try block and then handle the exception in the except block. An example of the class EmptyError is created using the variable var.
Code
class EmptyError( RuntimeError ):
def __init__(self, argument):
self.arguments = argument
Once the preceding class has been created, the following is how to raise an exception:
Code
var = " "
try:
raise EmptyError( "The variable is empty" )
except (EmptyError, var):
print( var.arguments )
Output: 2 try: —-> 3 raise EmptyError( “The variable is empty” ) 4 except (EmptyError, var): EmptyError: The variable is empty
Python Exceptions List
Here is the complete list of Python in-built exceptions.
Sr.No.
Name of the Exception
Description of the Exception
1
Exception
All exceptions of Python have a base class.
2
StopIteration
If the next() method returns null for an iterator, this exception is raised.
3
SystemExit
The sys.exit() procedure raises this value.
4
StandardError
Excluding the StopIteration and SystemExit, this is the base class for all Python built-in exceptions.
5
ArithmeticError
All mathematical computation errors belong to this base class.
6
OverflowError
This exception is raised when a computation surpasses the numeric data type’s maximum limit.
7
FloatingPointError
If a floating-point operation fails, this exception is raised.
8
ZeroDivisionError
For all numeric data types, its value is raised whenever a number is attempted to be divided by zero.
9
AssertionError
If the Assert statement fails, this exception is raised.
10
AttributeError
This exception is raised if a variable reference or assigning a value fails.
11
EOFError
When the endpoint of the file is approached, and the interpreter didn’t get any input value by raw_input() or input() functions, this exception is raised.
12
ImportError
This exception is raised if using the import keyword to import a module fails.
13
KeyboardInterrupt
If the user interrupts the execution of a program, generally by hitting Ctrl+C, this exception is raised.
14
LookupError
LookupErrorBase is the base class for all search errors.
15
IndexError
This exception is raised when the index attempted to be accessed is not found.
16
KeyError
When the given key is not found in the dictionary to be found in, this exception is raised.
17
NameError
This exception is raised when a variable isn’t located in either local or global namespace.
18
UnboundLocalError
This exception is raised when we try to access a local variable inside a function, and the variable has not been assigned any value.
19
EnvironmentError
All exceptions that arise beyond the Python environment have this base class.
20
IOError
If an input or output action fails, like when using the print command or the open() function to access a file that does not exist, this exception is raised.
22
SyntaxError
This exception is raised whenever a syntax error occurs in our program.
23
IndentationError
This exception was raised when we made an improper indentation.
24
SystemExit
This exception is raised when the sys.exit() method is used to terminate the Python interpreter. The parser exits if the situation is not addressed within the code.
25
TypeError
This exception is raised whenever a data type-incompatible action or function is tried to be executed.
26
ValueError
This exception is raised if the parameters for a built-in method for a particular data type are of the correct type but have been given the wrong values.
27
RuntimeError
This exception is raised when an error that occurred during the program’s execution cannot be classified.
28
NotImplementedError
If an abstract function that the user must define in an inherited class is not defined, this exception is raised.
Summary
We learned about different methods to raise, catch, and handle Python exceptions after learning the distinction between syntax errors and exceptions. We learned about these clauses in this tutorial:
We can throw an exception at any line of code using the raise keyword.
Using the assert keyword, we may check to see if a specific condition is fulfilled and raise an exception if it is not.
All statements are carried out in the try clause until an exception is found.
The try clause’s exception(s) are detected and handled using the except function.
If no exceptions are thrown in the try code block, we can write code to be executed in the else code block.
Here is the syntax of try, except, else, and finally clauses.
Syntax:
try:
# Code block
# These statements are those which can probably have some error
except:
# This block is optional.
# If the try block encounters an exception, this block will handle it.
else:
# If there is no exception, this code block will be executed by the Python interpreter
finally:
# Python interpreter will always execute this code.
Modular programming is the practice of segmenting a single, complicated coding task into multiple, simpler, easier-to-manage sub-tasks. We call these subtasks modules. Therefore, we can build a bigger program by assembling different modules that act like building blocks.
Modularizing our code in a big application has a lot of benefits.
Simplification: A module often concentrates on one comparatively small area of the overall problem instead of the full task. We will have a more manageable design problem to think about if we are only concentrating on one module. Program development is now simpler and much less vulnerable to mistakes.
Flexibility: Modules are frequently used to establish conceptual separations between various problem areas. It is less likely that changes to one module would influence other portions of the program if modules are constructed in a fashion that reduces interconnectedness. (We might even be capable of editing a module despite being familiar with the program beyond it.) It increases the likelihood that a group of numerous developers will be able to collaborate on a big project.
Reusability: Functions created in a particular module may be readily accessed by different sections of the assignment (through a suitably established api). As a result, duplicate code is no longer necessary.
Scope: Modules often declare a distinct namespace to prevent identifier clashes in various parts of a program.
In Python, modularization of the code is encouraged through the use of functions, modules, and packages.
What are Modules in Python?
A document with definitions of functions and various statements written in Python is called a Python module.
In Python, we can define a module in one of 3 ways:
Python itself allows for the creation of modules.
Similar to the re (regular expression) module, a module can be primarily written in C programming language and then dynamically inserted at run-time.
A built-in module, such as the itertools module, is inherently included in the interpreter.
A module is a file containing Python code, definitions of functions, statements, or classes. An example_module.py file is a module we will create and whose name is example_module.
We employ modules to divide complicated programs into smaller, more understandable pieces. Modules also allow for the reuse of code.
Rather than duplicating their definitions into several applications, we may define our most frequently used functions in a separate module and then import the complete module.
Let’s construct a module. Save the file as example_module.py after entering the following.
Example:
# Here, we are creating a simple Python program to show how to create a module.
# defining a function in the module to reuse it
def square( number ):
# here, the above function will square the number passed as the input
result = number ** 2
return result # here, we are returning the result of the function
Here, a module called example_module contains the definition of the function square(). The function returns the square of a given number.
How to Import Modules in Python?
In Python, we may import functions from one module into our program, or as we say into, another module.
For this, we make use of the import Python keyword. In the Python window, we add the next to import keyword, the name of the module we need to import. We will import the module we defined earlier example_module.
Syntax:
import example_module
The functions that we defined in the example_module are not immediately imported into the present program. Only the name of the module, i.e., example_ module, is imported here.
We may use the dot operator to use the functions using the module name. For instance:
Example:
# here, we are calling the module square method and passing the value 4
result = example_module.square( 4 )
print("By using the module square of number is: ", result )
Output:By using the module square of number is: 16
There are several standard modules for Python. The complete list of Python standard modules is available. The list can be seen using the help command.
Similar to how we imported our module, a user-defined module, we can use an import statement to import other standard modules.
Importing a module can be done in a variety of ways. Below is a list of them.
Python import Statement
Using the import Python keyword and the dot operator, we may import a standard module and can access the defined functions within it. Here’s an illustration.
Code
# Here, we are creating a simple Python program to show how to import a standard module
# Here, we are import the math module which is a standard module
import math
print( "The value of euler's number is", math.e )
# here, we are printing the euler's number from the math module
Output:The value of euler’s number is 2.718281828459045
Importing and also Renaming
While importing a module, we can change its name too. Here is an example to show.
Code
# Here, we are creating a simple Python program to show how to import a module and rename it
# Here, we are import the math module and give a different name to it
import math as mt # here, we are importing the math module as mt
print( "The value of euler's number is", mt.e )
# here, we are printing the euler's number from the math module
Output:The value of euler’s number is 2.718281828459045
The math module is now named mt in this program. In some situations, it might help us type faster in case of modules having long names.
Please take note that now the scope of our program does not include the term math. Thus, mt.pi is the proper implementation of the module, whereas math.pi is invalid.
Python from…import Statement
We can import specific names from a module without importing the module as a whole. Here is an example.
Code
# Here, we are creating a simple Python program to show how to import specific
# objects from a module
# Here, we are import euler's number from the math module using the from keyword
from math import e
# here, the e value represents the euler's number
print( "The value of euler's number is", e )
Output:The value of euler’s number is 2.718281828459045
Only the e constant from the math module was imported in this case.
We avoid using the dot (.) operator in these scenarios. As follows, we may import many attributes at the same time:
Code
# Here, we are creating a simple Python program to show how to import multiple
# objects from a module
from math import e, tau
print( "The value of tau constant is: ", tau )
print( "The value of the euler's number is: ", e )
Output:The value of tau constant is: 6.283185307179586 The value of the euler’s number is: 2.718281828459045
Import all Names – From import * Statement
To import all the objects from a module within the present namespace, use the * symbol and the from and import keyword.
Syntax:
from name_of_module import *
There are benefits and drawbacks to using the symbol *. It is not advised to use * unless we are certain of our particular requirements from the module; otherwise, do so.
Here is an example of the same.
Code
# Here, we are importing the complete math module using *
from math import *
# Here, we are accessing functions of math module without using the dot operator
print( "Calculating square root: ", sqrt(25) )
# here, we are getting the sqrt method and finding the square root of 25
print( "Calculating tangent of an angle: ", tan(pi/6) )
# here pi is also imported from the math module
Output:Calculating square root: 5.0 Calculating tangent of an angle: 0.5773502691896257
Locating Path of Modules
The interpreter searches numerous places when importing a module in the Python program. Several directories are searched if the built-in module is not present. The list of directories can be accessed using sys.path. The Python interpreter looks for the module in the way described below:
The module is initially looked for in the current working directory. Python then explores every directory in the shell parameter PYTHONPATH if the module cannot be located in the current directory. A list of folders makes up the environment variable known as PYTHONPATH. Python examines the installation-dependent set of folders set up when Python is downloaded if that also fails.
Here is an example to print the path.
Code
# Here, we are importing the sys module
import sys
# Here, we are printing the path using sys.path
print("Path of the sys module in the system is:", sys.path)
Output:Path of the sys module in the system is: [‘/home/pyodide’, ‘/home/pyodide/lib/Python310.zip’, ‘/lib/Python3.10’, ‘/lib/Python3.10/lib-dynload’, ”, ‘/lib/Python3.10/site-packages’]
The dir() Built-in Function
We may use the dir() method to identify names declared within a module.
For instance, we have the following names in the standard module str. To print the names, we will use the dir() method in the following way:
Code
# Here, we are creating a simple Python program to print the directory of a module
print( "List of functions:\n ", dir( str ), end=", " )
Objects are represented by names or identifiers called variables. A namespace is a dictionary containing the names of variables (keys) and the objects that go with them (values).
Both local and global namespace variables can be accessed by a Python statement. When two variables with the same name are local and global, the local variable takes the role of the global variable. There is a separate local namespace for every function. The scoping rule for class methods is the same as for regular functions. Python determines if parameters are local or global based on reasonable predictions. Any variable that is allocated a value in a method is regarded as being local.
Therefore, we must use the global statement before we may provide a value to a global variable inside of a function. Python is informed that Var_Name is a global variable by the line global Var_Name. Python stops looking for the variable inside the local namespace.
We declare the variable Number, for instance, within the global namespace. Since we provide a Number a value inside the function, Python considers a Number to be a local variable. UnboundLocalError will be the outcome if we try to access the value of the local variable without or before declaring it global.
Code
Number = 204
def AddNumber(): # here, we are defining a function with the name Add Number
# Here, we are accessing the global namespace
global Number
Number = Number + 200
print("The number is:", Number)
# here, we are printing the number after performing the addition
AddNumber() # here, we are calling the function
print("The number is:", Number)
In this tutorial, we are discussing Python file handling. Python supports the file-handling process. Till now, we were taking the input from the console and writing it back to the console to interact with the user. Users can easily handle the files, like read and write the files in Python. In another programming language, the file-handling process is lengthy and complicated. But we know Python is an easy programming language. So, like other things, file handling is also effortless and short in Python.
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 like a comma (,) or a newline character. Python executes the code line by line. So, it works in one line and then asks the interpreter to start the new line again. This is a continuous process in Python.
Hence, a file operation can be done in the following order.
Open a file
Read or write – Performing operation
Close the file
Opening a file
A file operation starts with the file opening. At first, open the File then Python will start the operation. File opening is done with the open() function in Python. This function will accepts two arguments, file name and access mode in which the file is accessed. When we use the open() function, that time we must be specified the mode for which the File is opening. The function returns a file object which can be used to perform various operations like reading, writing, etc.
Syntax:
The syntax for opening a file in Python is given below –
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 mode
Description
1
r
r means to read. So, it opens a file for read-only operation. The file pointer exists at the beginning. The file is by default open in this mode if no access mode is passed.
2
rb
It opens the file to read-only in binary format. The file pointer exists at the beginning of the file.
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.
5
w
It opens the file to write only. It overwrites the file if previously exists or creates a new one if no file exists with the same name. The file pointer exists at the beginning of the file.
6
wb
It opens the file to write only in binary format. It overwrites the file if it exists previously or creates a new one if no file exists. The file pointer exists at the beginning of the file.
7
w+
It opens the file to write and read both. It is different from r+ in the sense that it overwrites the previous file if one exists whereas r+ doesn’t overwrite the previously written file. It creates a new file if no file exists. 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.
10
ab
It opens the file in the append mode in binary format. The pointer exists at the end of the previously written file. It creates a new file in binary format if no file exists with the same name.
11
a+
It opens a file to append and read both. The file pointer remains at the end of the file if a file exists. It creates a new file if no file exists with the same name.
12
ab+
It opens a file to append and read both in binary format. The file pointer remains at the end of the file.
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.
Program code for read mode:
It is a read operation in Python. We open an existing file with the given code and then read it. The code is given below –
#opens the file file.txt in read mode
fileptr = open(“file.txt”,”r”)
if fileptr:
print(“file is opened successfully”)
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -<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
Program code for Write Mode:
It is a write operation in Python. We open an existing file using the given code and then write on it. The code is given below –
file = open('file.txt','w')
file.write("Here we write a command")
file.write("Hello users of JAVATPOINT")
file.close()
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below –
> Hi
ERROR!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Hi' is not defined
The close() Method
The close method used to terminate the program. Once all the operations are done on the file, we must close it through our Python script using the close() method. Any unwritten information gets destroyed once the close() method is called on a file object.
We can perform any operation on the file externally using the file system which is the currently opened in Python; hence it is good practice to close the file once all the operations are done. Earlier use of the close() method can cause the of destroyed some information that you want to write in your File.
The syntax to use the close() method is given below.
Syntax
The syntax for closing a file in Python is given below –
fileobject.close()
Consider the following example.
Program code for Closing Method:
Here we write the program code for the closing method in Python. The code is given below –
# opens the file file.txt in read mode
fileptr = open("file.txt","r")
if fileptr:
print("The existing file is opened successfully in Python")
#closes the opened file
fileptr.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.
We should use the following method to overcome such type of problem.
The with statement was introduced in python 2.5. The with statement is useful in the case of manipulating the files. It is used in the scenario where a pair of statements is to be executed with a block of code in between.
Syntax:
The syntax of with statement of a file in Python is given below –
with open(<file name>, <access mode>) as <file-pointer>:
#statement suite
The advantage of using with statement is that it provides the guarantee to close the file regardless of how the nested block exits.
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.
Program code 1 for with statement:
Here we write the program code for with statement in Python. The code is given below –
with open("file.txt",'r') as f:
content = f.read();
print(content)
Program code 2 for with statement:
Here we write the program code for with statement in Python. The code is given below –
with open("file.txt", "H") as f:
A = f.write("Hello Coders")
Print(A)
Writing the file
To write some text to a file, we need to open the file using the open method and then we can use the write method for writing in this File. If we want to open a file that does not exist in our system, it creates a new one. On the other hand, if the File exists, then erase the past content and add new content to this File. the It is done by the following access modes.
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.
Program code 1 for Write Method:
Here we write the program code for write method in Python. The code is given below –
# open the file.txt in append mode. Create a new file if no such file exists.
fileptr = open("file2.txt", "w")
# appending the content to the file
fileptr.write(''''''''Python is the modern programming language. It is done any kind of program in shortest way.''')
# closing the opened the file
fileptr.close()
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -File2.txt Python is the modern programming language. It is done any kind of program in shortest way.
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
Program code 2 for Write Method:
Here we write the program code for write method in Python. The code is given below –
with open(test1.txt’, ‘w’) as file2:
file2.write(‘Hello coders’)
fil2.write(‘Welcome to javaTpoint’)
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -Hello coders Welcome to javaTpoint
Program code 3 for Write Method:
Here we write the program code for write method in Python. The code is given below –
#open the file.txt in write mode.
fileptr = open("file2.txt","a")
#overwriting the content of the file
fileptr.write(" Python has an easy syntax and user-friendly interaction.")
#closing the opened file
fileptr.close()
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -Python is the modern day language. It makes things so simple. It is the fastest growing language Python has an easy syntax and user-friendly interaction.
Snapshot of the file2.txt
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.
Syntax:
The syntax of read() method of a file in Python is given below –
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.
Program code for read() Method:
Here we write the program code for read() method in Python. The code is given below –
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open(“file2.txt”,”r”)
#stores all the data of the file into the variable content
content = fileptr.read(10)
# prints the type of the data stored in the file
print(type(content))
#prints the content of the file
print(content)
#closes the opened file
fileptr.close()
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -<class ‘str’> Python is
In the above code, we have read the content of file2.txt by using the read() function. We have passed count value as ten which means it will read the first ten characters from the file.
If we use the following line, then it will print all content of the file. So, it only prints ‘Python is’. For read the whole file contents, the code is given below –
content = fileptr.read()
print(content)
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -Python is the modern-day language. It makes things so simple. It is the fastest-growing programming language Python has easy an syntax and user-friendly interaction.
Read file through for loop
We can use read() method when we open the file. Read method is also done through the for loop. We can read the file using for loop. Consider the following example.
Program code 1 for Read File using For Loop:
Here we give an example of read file using for loop. The code is given below –
#open the file.txt in read mode. causes an error if no such file exists.
fileptr = open("file2.txt","r");
#running a for loop
for i in fileptr:
print(i) # i contains each line of the file
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -Python is the modern day language. It makes things so simple. Python has easy syntax and user-friendly interaction.
Program code 2 for Read File using For Loop:
Here we give an example of read file using for loop. The code is given below –
A = ["Hello\n", "Coders\n", "JavaTpoint\n"]
f1 = open('myfile.txt', 'w')
f1.writelines(A)
f1.close()
f1 = open('myfile.txt', 'r')
Lines = f1.read()
count = 0
for line in Lines:
count += 1
print("Line{}: {}".format(count, line.strip()))
Output:Line1: H Line2: e Line3: l Line4: l Line5: o Line6: Line7: C Line8: o Line9: d Line10: e Line11: r Line12: s Line13: Line14: J Line15: a Line16: v Line17: a Line18: T Line19: p Line20: o Line21: i Line22: n Line23: t Line24:
Read Lines of the file
Python facilitates to read the file line by line by using a function readline() method. The readline() method reads the lines of the file from the beginning, i.e., if we use the readline() method two times, then we can get the first two lines of the file.
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.
Here we give the example of reading the lines using the readline() function in Python. The code is given below –
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file2.txt","r");
#stores all the data of the file into the variable content
content = fileptr.readline()
content1 = fileptr.readline()
#prints the content of the file
print(content)
print(content1)
#closes the opened file
fileptr.close()
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -Python is the modern day language. It makes things so simple.
We called the readline() function two times that’s why it read two lines from the file.That means, if you called readline() function n times in your program, then it read n number of lines from the file. This is the uses of readline() function in Python. 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.
Example 2:
Here we give the example of reading the lines using the readline() function in Python. The code is given below –
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file2.txt","r");
#stores all the data of the file into the variable content
content = fileptr.readlines()
#prints the content of the file
print(content)
#closes the opened file
fileptr.close()
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -[‘Python is the modern day language.\n’, ‘It makes things so simple.\n’, ‘Python has easy syntax and user-friendly interaction.’]
Example 3:
Here we give the example of reading the lines using the readline() function in Python. The code is given below –
A = ["Hello\n", "Coders\n", "JavaTpoint\n"]
f1 = open('myfile.txt', 'w')
f1.writelines(A)
f1.close()
f1 = open('myfile.txt', 'r')
Lines = f1.readlines()
count = 0
for line in Lines:
count += 1
print("Line{}: {}".format(count, line.strip()))
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -Line1: Hello Line2: Coders Line3: JavaTpoint
Creating a new file
The new file can be created by using one of the following access modes with the function open().The open() function used so many parameters. The syntax of it is given below –
file = open(path_to_file, mode)
x, a and w is the modes of open() function. The uses of these modes are given below –
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.
Consider the following example.
Program code1 for Creating a new file:
Here we give an example for creating a new file in Python. For creates a file, we have to used the open() method. The code is given below –
#open the file.txt in read mode. causes error if no such file exists.
fileptr = open("file2.txt","x")
print(fileptr)
if fileptr:
print("File created successfully")
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -<_io.TextIOWrapper name=’file2.txt’ mode=’x’ encoding=’cp1252′> File created successfully
Program code2 for creating a new file:
Here we give an example for creating a new file in Python. For creates a file, we have to use the open() method. Here we use try block for erase the errors. The code is given below –
try:
with open('file1.txt', 'w') as f:
f.write('Here we create a new file')
except FileNotFoundError:
print("The file is does not exist")
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -The file is does not exist
File Pointer positions
Python provides the tell() method which is used to print the byte number at which the file pointer currently exists. The tell() methods is return the position of read or write pointer in this file. The syntax of tell() method is given below –
fileobject.tell()
Program code1 for File Pointer Position:
Here we give an example for how to find file pointer position in Python. Here we use tell() method and it is return byte number. The code is given below –
# open the file file2.txt in read mode
fileptr = open("file2.txt","r")
#initially the filepointer is at 0
print("The filepointer is at byte :",fileptr.tell())
#reading the content of the file
content = fileptr.read();
#after the read operation file pointer modifies. tell() returns the location of the fileptr.
print("After reading, the filepointer is at:",fileptr.tell())
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -The filepointer is at byte : 0 After reading, the filepointer is at: 117
Program code2 for File Pointer Position:
file = open("File2.txt", "r")
print("The pointer position is: ", file.tell())
Here we give another example for how to find file pointer position in Python. Here we also use tell() method, which is return byte number. The code is given below – Here we give another example for how to find file pointer position in Python. Here we also use tell() method, which is return byte number. The code is given below –
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below – The pointer position is: 0
Modifying file pointer position
In real-world applications, sometimes we need to change the file pointer location externally since we may need to read or write the content at various locations.
For this purpose, the Python provides us the seek() method which enables us to modify the file pointer position externally. That means, using seek() method we can easily change the cursor in the file, from where we want to read or write a file.
Syntax:
The syntax for seek() method is given below –
<file-ptr>.seek(offset[, from)
The seek() method accepts two parameters:
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.
Consider the following example.
Here we give the example of how to modifying the pointer position using seek() method in Python. The code is given below –
# open the file file2.txt in read mode
fileptr = open("file2.txt","r")
#initially the filepointer is at 0
print("The filepointer is at byte :",fileptr.tell())
#changing the file pointer location to 10.
fileptr.seek(10);
#tell() returns the location of the fileptr.
print("After reading, the filepointer is at:",fileptr.tell())
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -The filepointer is at byte : 0 After reading, the filepointer is at: 10
Python OS module:
Renaming the file
The Python os module enables interaction with the operating system. It comes from the Python standard utility module. The os module provides a portable way to use the operating system-dependent functionality in Python. 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. Using the rename() method, we can easily rename the existing File. This method has not any return value. The syntax to use the rename() method is given below.
Syntax:
The syntax of rename method in Python is given below –
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.
Program code 1 for rename() Method:
Here we give an example of the renaming of the files using rename() method in Python. The current file name is file2.txt, and the new file name is file3.txt. The code is given below –
import os
#rename file2.txt to file3.txt
os.rename("file2.txt","file3.txt")
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -The above code renamed current file2.txt to file3.txt
Program code 2 for rename() Method:
Here we give an example of the renaming of the files using rename() method in Python. The current file name is the source, and the new file name is the destination. The code is given below –
import os
def main():
i = 0
path="D:/JavaTpoint/"
for filename in os.listdir(path):
destination = "new" + str(i) + ".png"
source = path + filename
destination = path + destination
os.rename(source, destination)
i += 1
if __name__ == '__main__':
main()
Removing the file
The os module provides the remove() method which is used to remove the specified file.
Syntax:
The syntax of remove method is given below –
remove(file-name)
Program code 1 for remove() method:
import os;
#deleting the file named file3.txt
os.remove("file3.txt")
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below – The file named file3.txt is deleted.
Program code 2 for remove() Method:
Here we give an example of removing a file using the remove() method in Python. The file name is file3.txt, which the remove() method deletes. Print the command “This file is not existed” if the File does not exist. The code is given below –
import os
if os.path.exists("file3.txt "):
os.remove("file3.txt ")
else:
print("This file is not existed")
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below – This file is not existed
Creating the new directory
The mkdir() method is used to create the directories in the current working directory.It creates dictionary in numeric mode. If the file already presents in the system, then it occurs error, which is known as FileExistsError in Python. The mkdir() method does not return any kind of value. The syntax to create the new directory is given below.
Syntax:
The syntax of mkdir() method in Python is given below –
os.mkdir (path, mode = 0o777, *, dir_fd = None)
Output:
Parameter:
The syntax of mkdir() method in Python is given below –
path – A path like object represent a path either bytes or the strings object.
mode – Mode is represented by integer value, which means mode is created. If mode is not created then the default value will be 0o777. Its use is optional in mkdir() method.
dir_fd – When the specified path is absolute, in that case dir_fd is ignored. Its use is optional in mkdir() method.
Program code 1 for mkdir() Method:
Here we give the example of mkdir() method by which we can create new dictionary in Python. The code is given below –
import os
#creating a new directory with the name new
os.mkdir("new")
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -Create a new dictionary which is named new
Program code 2 for mkdir() Method:
Here we give the example of mkdir() method by which we can create new dictionary in Python. The code is given below –
import os
path = '/D:/JavaTpoint'
try:
os.mkdir(path)
except OSError as error:
print(error)
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below – [Error 20] File exists: ‘/D:/JavaTpoint’
The getcwd() method:
This method returns the current working directory which have absolute value. The getcwd() method returns the string value which represents the working dictionary in Python. In getcwd() method, do not require any parameter.
The syntax to use the getcwd() method is given below.
Syntax
The syntax of getcwd() method in Python is given below –
os.getcwd()
Program code 1 for getcwd() Method:
Here we give the example of getcwd() method by which we can create new dictionary in Python. The code is given below –
import os
os.getcwd()
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -‘C:\\Users\\DEVANSH SHARMA’
Program code 2 for getcwd() Method:
Here we give the example of getcwd() method by which we can create new dictionary in Python. The code is given below –
import os
c = os.getcwd()
print("The working directory is:", c)
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -The working directory is: C:\\Users\\JavaTpoint
Changing the current working directory
The chdir() method is used to change the current working directory to a specified directory.The chdir() method takes a single argument for the new dictionary path. The chdir() method does not return any kind of value.
Syntax
The syntax of chdir() method is given below –
chdir("new-directory")
Program code 1 for chdir() Method:
Here we give the example of chdir() method by which we can change the current working dictionary into new dictionary in Python. The code is given below –
import os
# Changing current directory with the new directiory
os.chdir("C:\\Users\\DEVANSH SHARMA\\Documents")
#It will display the current working directory
os.getcwd()
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -‘C:\\Users\\DEVANSH SHARMA\\Documents’
Program code 2 for chdir() Method:
Here we give another example of chdir() method by which we can change the current working dictionary into new dictionary in Python. The code is given below –
import os
os.chdir(r"C:\Users\JavaTpoint")
print("Currently working directory is changed")
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -Currently working directory is changed
Deleting directory:
The rmdir() method is used to delete the specified directory. If the directory is not empty then there is occurs OSError. The rmdir() method does not have and kind of return value.
Syntax
os.rmdir(directory name)
Program code 1 for rmdir() Method:
Here we give the example of rmdir() method by which we can delete a dictionary in Python. The code is given below –
import os
#removing the new directory
os.rmdir("directory_name")
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -It will remove the specified directory.
Program code 2 for rmdir() Method:
Here we give another example of rmdir() method by which we can delete a dictionary in Python. The code is given below –
import os
directory = "JavaTpoint"
parent = "/D:/User/Documents"
path = os.path.join(parent, directory)
os.rmdir(path)
print("The directory '%s' is successfully removed", %directory)
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -The directory ‘JavaTpoint’ is successfully removed
Output:
Here we give the example of rmdir() method by which we can delete a dictionary in Python. Here we use try block for handle the error. The code is given below –
import os
dir = "JavaTpoint"
parent = "/D:/User/Documents"
path = os.path.join(parent, dir)
try:
os.rmdir(path)
print("The directory '%s' is successfully removed", %dir)
except OSError as error:
print(error)
print("The directory '%s' cannot be removed successfully", %dir)
Output:
Now we compile the above code in Python, and after successful compilation, we run it. Then the output is given below -[Error 30] Permission denied: ‘/D:/User/Documents/JavaTpoint’ The directory ‘JavaTpoint’ cannot be removed successfully
Writing Python output to the files:
In Python, there are the requirements to write the output of a Python script to a file.
The check_call() method of module subprocess is used to execute a Python script and write the output of that script to a file.
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.
Program code:
file1.py
temperatures=[10,-20,-289,100]
def c_to_f(c):
if c< -273.15:
return "That temperature doesn't make sense!"
else:
f=c*9/5+32
return f
for t in temperatures:
print(c_to_f(t))
file.py
import subprocess
with open("output.txt", "wb") as f:
subprocess.check_call(["python", "file.py"], stdout=f)
File Related Methods:
The file object provides the following methods to manipulate the files on various operating systems. Here we discuss the method and their uses in Python.
SN
Method
Description
1
file.close()
It closes the opened file. The file once closed, it can’t be read or write anymore.
2
File.fush()
It flushes the internal buffer.
3
File.fileno()
It returns the file descriptor used by the underlying implementation to request I/O from the OS.
4
File.isatty()
It returns true if the file is connected to a TTY device, otherwise returns false.
5
File.next()
It returns the next line from the file.
6
File.read([size])
It reads the file for the specified size.
7
File.readline([size])
It reads one line from the file and places the file pointer to the beginning of the new line.
8
File.readlines([sizehint])
It returns a list containing all the lines of the file. It reads the file until the EOF occurs using readline() function.
9
File.seek(offset[,from)
It modifies the position of the file pointer to a specified offset with the specified reference.
10
File.tell()
It returns the current position of the file pointer within the file.
11
File.truncate([size])
It truncates the file to the optional specified size.
12
File.write(str)
It writes the specified string to a file
13
File.writelines(seq)
It writes a sequence of the strings to a file.
Conclusion:
In this tutorial, we briefly discussed the Python file handling. Users can easily handle the files, like read and write the files in Python. Here we discuss various methods in Python by which we can easily read, write, delete, or rename a file. We also give the program code of these methods for better understanding.