Unit V Python
Unit V Python
Close Files
It is a good practice to always close the file when you are done with it.
Example
Close the file when you are finished with it:
f = open("[Link]", "r")
print([Link]())
[Link]()
Create a New File
To create a new file in Python, use the open() method, with one of the following
parameters:
"x" - Create - will create a file, returns an error if the file exists
"a" - Append - will create a file if the specified file does not exists
"w" - Write - will create a file if the specified file does not exists
Example
Create a file called "[Link]":
f = open("[Link]", "x")
Result: a new empty file is created!
Example
Create a new file if it does not exist:
f = open("[Link]", "w")
Delete a File
To delete a file, you must import the OS module, and run its [Link]() function:
Remove the file "[Link]":
import os
[Link]("[Link]")
Delete Folder
To delete an entire folder, use the [Link]() method:
Example
Remove the folder "myfolder":
import os
[Link]("myfolder")
4.2 Directory
Get Current Working Directory
To retrieve the current working directory in Python, you can use
the [Link]() function. This function returns a string representing the current working
directory where the Python script is executing.
Syntax
Following is the basic syntax of the getcwd() function in Python −
[Link]()
Example
Following is an example to display the current working directory using the getcwd() function −
Open Compiler
import os
current_directory = [Link]()
print(f"Current working directory: {current_directory}")
We get the output as follows −
Current working directory: /home/cg/root/667ba7570a5b7
try:
[Link](new_directory)
print(f"Current working directory changed to '{new_directory}'.")
except OSError as e:
print(f"Error: Failed to change working directory to '{new_directory}'. {e}")
We get the output as shown below −
Current working directory changed to 'D:\MyFolder\Pictures'.
Removing a Directory
You can remove an empty directory in Python using the [Link]() method. If the
directory contains files or other directories, you can use [Link]() method to delete
it recursively.
Syntax
Following is the basic syntax to delete a directory in Python −
[Link](directory_path)
# or
[Link](directory_path)
Example
In the following example, we remove an empty directory using the [Link]() method −
import os
directory_path = r"D:\MyFolder\new_dir"
try:
[Link](directory_path)
print(f"Directory '{directory_path}' successfully removed.")
except OSError as e:
print(f"Error: Failed to remove directory '{directory_path}'. {e}")
It will produce the following output −
Directory 'D:\MyFolder\new_dir' successfully removed.
Output:
Display the Python calendar of the given Year
The code you provided uses Python’s calendar module to print a calendar for the year
2018.
import calendar
print ("The calendar of year 2018 is : ")
print ([Link](2018))
class [Link]
The calendar class creates a calendar object. A calendar object provides several
methods that can be used for preparing the calendar data for formatting. This class doesn’t do
any formatting itself. This is the job of subclasses. The calendar class allows the calculations
for various tasks based on date, month, and year and provides the following methods:
Function Description
iterweekdays() Returns an iterator for the weekday numbers that will be used for one week
itermonthdates() Returns an iterator for the month (1–12) in the year
itermonthdays() Returns an iterator of a specified month and a year
class [Link]
TextCalendar class can be used to generate plain text calendars. TextCalendar class in
Python allows you to edit the calendar and use it as per your requirement.
Function Description
formatmonth() This method is used to get the month’s
calendar in a multi-line string
prmonth() This method is used to print a month’s
calendar as returned by formatmonth()
formatyear() This method is used to get m-column
calendar for an entire year as a multi-line
string
class [Link] :
HTMLCalendar class can be used to generate HTML calendars. HTMLCalendar class
in Python allows you to edit the calendar and use as per your requirement.
Function Description
formatmonth() This method is used to get the month’s
calendar as an HTML table
formatyear() This method is used to get a year’s
calendar as an HTML table.
formatyearpage() This method is used to get the year’s
calendar as a complete HTML page
time3 = time()
print("time", time3)
Class attributes
1. [Link] − The earliest representable time, time(0, 0, 0, 0).
2. [Link] − The latest representable time, time(23, 59, 59, 999999).
3. [Link] − The smallest possible difference between non-equal time objects.
Example
Open Compiler
from datetime import time
print([Link])
print([Link])
print ([Link])
It will produce the following output −
[Link]
[Link].999999
[Link].000001
Instance attributes
1. [Link] − In range(24)
2. [Link] − In range(60)
3. [Link] − In range(60)
4. [Link] − In range(1000000)
5. [Link] − the tzinfo argument to the time constructor, or None.
Example
from datetime import time
t = time(8,23,45,5000)
print([Link])
print([Link])
print ([Link])
print ([Link])
It will produce the following output −
8
23
455000
Concurrency in Python
Concurrency is one approach to drastically increase the performance of your Python
programs. Concurrency allows several processes to be completed concurrently, maximizing the
utilization of your system’s resources. Concurrency can be achieved in Python by the use of
numerous methods and modules, such as threading, multiprocessing, and asynchronous
programming. In this article, we will learn about What is concurrency in Python, the processes
required to implement it, some good examples, and the output results.
What is Concurrent Programming?
It refers to the ability of the computer to manage multiple tasks at the same time. These
tasks might not be compulsory to execute at the exact same moment but they might interleaved
or executed in overlapping periods of time. The main goal of concurrency is to handle multiple
user inputs, manage several I/O tasks, or process multiple independent tasks.
What is Parallelism?
Parallelism is a subset of concurrency where tasks or processes are executed
simultaneously, As we know concurrency is about dealing with multiple tasks, whereas
parallelism is about executing them simultaneously to speed computation. The primary goal is
to improve computational efficiency and speed up the [performance of the system.
Thread-Based Concurrency: Threading is a technique for producing lightweight threads
(sometimes known as “worker threads”) in a single step. Because these threads share the same
memory region, they are ideal for I/O-bound activities.
Process-Based Concurrency: Multiprocessing entails the execution of several
processes, each with its own memory space. Because it can use several CPU cores, this is
appropriate for CPU-bound activities.
Coroutine-Based Concurrency: Asynchronous programming, with ‘asyncio’ , ‘async’, and
‘await’ keywords, is ideal for efficiently managing I/O-bound processes. It enables tasks to
pause and hand over control to other tasks during I/O operations without causing the entire
program to crash.
Concurrency vs. Parallelism
Concurrency: It refers to the execution of many tasks in overlapping time periods, but
not necessarily concurrently. It is appropriate for I/O-bound operations that frequently
rely on external resources such as files or network data.
Parallelism: On the other hand, is running many processes at the same time, generally
using multiple CPU cores. It is best suited for CPU-intensive jobs requiring lengthy
processing.
Steps to Implement Concurrency in Python
Select the Appropriate Approach:Determine whether your software is CPU or I/O
bound. Threading is best for I/O-bound operations whereas multiprocessing is best for
CPU-bound workloads.
Import the Appropriate Libraries: Import the threading, multiprocessing, or asyncio
libraries, depending on your method.
Create Worker Roles: Define the functions or methods that represent the jobs you
want to run simultaneously.
Create Threads, Processes, and Tasks: To execute your worker functions
concurrently, create and launch threads, processes, or asynchronous tasks.
Control Synchronization (if necessary): When employing threads or processes, use
synchronization methods such as locks or semaphores to prevent data corruption in
shared resources.
Wait for the job to be finished: Make sure your main application waits for all
concurrent jobs to finish before continuing.
Thread-Based Concurrency
Import the time and threading modules. Print_numbers and print_letters are two
functions that simulate time-consuming jobs. To imitate a time-consuming task, these
programs print numbers and letters with a 1-second delay between each print. Create
two Thread objects, thread1 and thread2, and use the target argument to assign each to
one of the functions (print_numbers and print_letters). Use the start() function to start
both threads. This starts the parallel execution of the functions. Use the join()
method for each thread to ensure that the main thread waits for threads 1 and 2 to finish
before continuing. This synchronization step is required to avoid the main program
ending prematurely. Finally, print a message indicating that both threads are complete.
import threading
import time
# Function to simulate a time-consuming task
def print_numbers():
for i in range(1, 6):
print(f"Printing number {i}")
[Link](1) # Simulate a delay of 1 second
# Function to simulate another task
def print_letters():
for letter in 'Geeks':
print(f"Printing letter {letter}")
[Link](1) # Simulate a delay of 1 second
# Create two thread objects, one for each function
thread1 = [Link](target=print_numbers)
thread2 = [Link](target=print_letters)
Output:
Printing number 1
Printing letter G
Printing number 2
Printing letter e
Printing letter e
Printing number 3
Printing letter k
Printing number 4
Printing letter s
Printing number 5
Both threads have finished.
When you run this code, you’ll notice that the two threads execute the two functions,
print_numbers and print_letters, concurrently. As a result, the output from both methods will
be interleaved, and each function will introduce a 1-second delay between prints, imitating a
time-consuming operation. The join() functions ensure that the main program awaits the
completion of both threads before printing the final message.
Process-Based Concurrency
Bring the multiprocessing module into the program. Define a square(x) function that
squares a given [Link] a number list with the integers [1, 2, 3, 4, 5].Using
multiprocessing, create a multiprocessing pool. To manage worker processes, use Pool().Apply
the square function to each number concurrently with [Link]() to distribute the work among
[Link] a list of the squared result and then print the values that have been squared
import multiprocessing
# Function to square a number
def square(x):
return x * x
if __name__ == "__main__":
# Define a list of numbers
numbers = [1, 2, 3, 4, 5]
This code parallelizes the square function on each number, utilizing many CPU cores for
quicker execution of CPU-bound operations.
Coroutine-Based Concurrency (using asyncio)
The code is broken down as follows: For asynchronous programming, import the
asyncio [Link] await [Link](1), define an asynchronous function greet(name)
that simulates a greeting with a 1-second [Link] the asynchronous main function
main().To schedule the greet function for each name concurrently, use [Link]().Run
the main asynchronous function using asyncio in the if __name__ == “__main__”:
[Link](main()).
import asyncio
async def greet(name):
await [Link](1)
print(name)
async def main():
await [Link](greet("Geeks"), greet("For"), greet("Geeks"))
# If in a Jupyter notebook or IPython environment:
import nest_asyncio
nest_asyncio.apply()
if __name__ == "__main__":
asyncio.create_task(main())
Output:
Geeks
For
Geeks
Queue in Python
Last Updated : 09 Jul, 2024
Like a stack, the queue is a linear data structure that stores items in a First In First Out
(FIFO) manner. With a queue, the least recently added item is removed first. A good example
of a queue is any queue of consumers for a resource where the consumer that came first is
served first.
Operations associated with queue are:
Enqueue: Adds an item to the queue. If the queue is full, then it is said to be an
Overflow condition – Time Complexity : O(1)
Dequeue: Removes an item from the queue. The items are popped in the same order in
which they are pushed. If the queue is empty, then it is said to be an Underflow
condition – Time Complexity : O(1)
Front: Get the front item from queue – Time Complexity : O(1)
Rear: Get the last item from queue – Time Complexity : O(1)
Initial queue
deque(['a', 'b', 'c'])
Elements dequeued from the queue
a
b
c
Queue after removing elements
deque([])
Implementation using [Link]
Queue is built-in module of Python which is used to implement a queue.
[Link](maxsize) initializes a variable to a maximum size of maxsize. A maxsize
of zero ‘0’ means a infinite queue. This Queue follows FIFO rule.
There are various functions available in this module:
maxsize – Number of items allowed in the queue.
empty() – Return True if the queue is empty, False otherwise.
full() – Return True if there are maxsize items in the queue. If the queue was initialized
with maxsize=0 (the default), then full() never returns True.
get() – Remove and return an item from the queue. If queue is empty, wait until an item
is available.
get_nowait() – Return an item if one is immediately available, else raise QueueEmpty.
put(item) – Put an item into the queue. If the queue is full, wait until a free slot is
available before adding the item.
put_nowait(item) – Put an item into the queue without blocking. If no free slot is
immediately available, raise QueueFull.
qsize() – Return the number of items in the queue.
Example: This code utilizes the Queue class from the queue module. It starts with an empty
queue and fills it with ‘a’, ‘b’, and ‘c’. After dequeuing, the queue becomes empty, and ‘1’ is
added. Despite being empty earlier, it remains full, as the maximum size is set to 3. The code
demonstrates queue operations, including checking for fullness and emptiness.
from queue import Queue
q = Queue(maxsize = 3)
print([Link]())
[Link]('a')
[Link]('b')
[Link]('c')
print("\nFull: ", [Link]())
print("\nElements dequeued from the queue")
print([Link]())
print([Link]())
print([Link]())
print("\nEmpty: ", [Link]())
[Link](1)
print("\nEmpty: ", [Link]())
print("Full: ", [Link]())
Output:
0
Full: True
Elements dequeued from the queue
a
b
c
Empty: True
Empty: False
Full: False
What Is a Thread
The [Link] class represents a thread of execution in Python.
There are two main ways to use a Thread; they are:
Execute a target function in a new thread.
Extend the Thread class and override run().
Run a Target Function in New Thread
The [Link] class can execute a target function in another thread.
This can be achieved by creating an instance of the [Link] class and
specifying the target function to execute via the target keyword.
The thread can then be started by calling the start() function and it will execute the
target function in another thread.
For example:
# a target function that does something
def work()
# do something...
Overriding the [Link] class offers more flexibility than calling a target function. It
allows the object to have multiple functions and to have object member variables for storing
state.
Extending the [Link] class is suited for longer-lived tasks and perhaps services
within an application.
What Is a Process
The [Link] class represents an instance of the Python interpreter for
running code.
There are two main ways to use a Process; they are:
Execute a target function in a new process.
Extend the Process class and override run().
Run a Target Function in New Process
The [Link] class can execute a target function in another process.
This can be achieved by creating an instance of the [Link] class and
specifying the target function to execute via the target keyword.
The process can then be started by calling the start() function and it will execute the target
function in a new child process.
For example:
# a target function that does something
def work()
# do something...
If the target function takes arguments, they can be specified via the args argument that takes a
tuple or the kwargs argument that takes a dictionary.
For example:
1 ...
2 # create a process to execute the work() function
3 process = Process(target=work, args=(123,))
The target task function is useful for executing one-off ad hoc tasks that probably don’t
interact with external state other than passed-in arguments and do not return a value
Extend the Process Class
The [Link] class can be extended for tasks that may involve multiple
functions and maintain state.
This can be achieved by extending the [Link] class and overriding
the run() function. The overridden run() function is then executed when the start() function of
the process is called.
For example:
Output:
Explanation:
In the above code, we have initialized the n variable to enter the number of rows for the pattern.
We entered n = 5, the range of outer for loop will be 0 to 4.
o The iteration of the inner for loop depends on the outer loop. The inner loop is
responsible to print the number of columns.
o In the first iteration, the value of i is 0, and it increased by 1, so it becomes 0+1, now
inner loop iterated first time and print one star(*).
o In the second iteration, the value of i is 1 and it increased by 1, so it becomes 1+1, now
inner loop iterated two times and print two-star (*).
o The end argument prevents to jump into another line. It will printer the star until the
loop is valid.
o The last print statement is responsible for ending the line after each row.
PubSub Model in Python
The publish/subscribe (pub/sub) model is a messaging pattern in which
publishers send messages to a message broker, and subscribers express interest in
receiving certain messages. The message broker is responsible for delivering the
messages to the subscribed clients.
Publishers and subscribers are separated in the pub/sub paradigm, so they can
communicate without being aware of one another’s existence. Because publishers and
subscribers can be added or removed without affecting others, this enables a more
flexible and scalable system.
Message queues, event buses, and topic-based publish/subscribe systems are just a few
of the technologies that can be used to construct pub/sub systems. They are frequently
employed in event-driven, distributed, and microservices designs.
In this tutorial, we are going to learn by example, how to implement pub/sub in Python.
Topics in Pub/Sub :
In a publish/subscribe system, topics are used to categorize messages and allow
subscribers to express interest in specific types of messages.
In a topic-based publish/subscribe system, publishers send messages to specific topics,
and subscribers express interest in one or more topics. The message broker is
responsible for delivering the messages to the subscribed clients.
For example, In a news publishing system, there may be topics for different categories
of news, such as politics, sports, and entertainment. Subscribers can express interest in
receiving messages on specific topics, such as only sports and entertainment. When a
publisher sends a message on the sports topic, it will be delivered to all subscribers
interested in that topic
.
Using topics allows for more fine-grained control over the messages that are
delivered to subscribers, as they can choose to receive only the messages that are
relevant to them. It also allows for a more scalable system, as publishers and subscribers
do not need to be aware of each other’s specific identities.
Events in pub/sub :
Events are messages that are published by a publisher and delivered to subscribed
clients. An event is typically a notification of something that has happened or is about to
happen. It can contain data about the event, such as the event type, a description, and any
relevant details. In an event-driven architecture, events are used to trigger actions or
behaviours in other parts of the system. For example, an event might be used to notify a
service that a new user has signed up, or that a payment has been processed. The service can
then respond to the event by performing some action, such as sending a welcome email or
updating a database. Using events allows for a more flexible and scalable system, as publishers
and subscribers do not need to be directly coupled and can communicate asynchronously. It
also allows for a more decoupled and modular system, as components can respond to events
without the need to be aware of the specific identities of the publishers.
Event Bus :
An event bus is a messaging system that allows publishers to send events to subscribers.
It is a type of publish/subscribe system that is commonly used in event-driven architectures.
In an event bus, events are published to a central message broker, which is responsible for
delivering the events to the subscribed clients. Subscribers express interest in receiving events
by registering with the event bus and specifying a list of events that they want to receive.