Tuesday, 19 November 2024

Modules and Regular Expressions in Python.


 

Everyone knows what function is. A block of reusable code that performs specific task. Through function we can organize the code properly, making it more readable and reusable.

Now, question comes to mind that what is a module? why do we require module? How to create a module?

Let's first start with the question why do we require module?

To enhance the modularity of code or project, you can wrap or define more than one related function together and load these functionalities inside another program as and when required.

what is a module?

A module is a block or file consist of classes, variables, constants, definition of functions or any other python object.

or

A file containing more than one related function you want to include in your program just like a code library.

can any program access this module for reusability?

Yes, all the content available inside this module made available to any other program.

Now, next question comes to our mind is how we can access this in our program but before this How to create a module?

Let's create a simple module:

Step 1: First decide what name you want to give to your module. for example, if i want to create "JSPM" module.

Step 2: Create a file JSPM.py and write all the related code inside this file to make it a module.

def welcome (name):

    print ("Hello, "+name+ "Welcome to JSPM University")


# Can we create object of subject's information in module?

Yes,

FPP = {
  "Teachername""Nitin Shivale",
  "age"36,
  "Subjectname""Fundamentals of python programming"
}


Step 3: JSPM Module is created with one welcome () function and one variable FPP of type dictionary in it. As we know we can create variable of all types like array, dictionary, objects etc. Now next task is we want to access all the functionalities available inside JSPM Module in another program. so, how we are going to access it?

Step 4: Suppose i have created the python file of name Admission.py and inside this file i want to write a code to greet all the students who are taking admission in JSPM University. Now we know that functionality is already available inside JSPM Module. no need to write same code once again so simply reuse that code by importing the functionality of that module inside our program.


import JSPM

name = input ("Enter the name of newly admitted student:")

JSPM.welcome (name)

After execution of this code message will display as follows:

Enter the name of newly admitted student: Tejas Bhosale

suppose if you enter the name = "Tejas Bhosale" then it will give us the output: Hello Tejas Bhosale Welcome to JSPM University

Can i create alias of my module and use it to access the functionality of module?

Yes, we can do this it's very simple just use the as keyword to do this.

import JSPM as ju

a = ju.FPP["Teachername"]
print(a)

Here after execution, you will get the output as follows:

Nitin Shivale


Q. Can i import only the required functionalities from the module instead of importing whole module?

Yes, you can suppose from the above example instead of calling all the functionalities i just wanted to import only dictionary variable that is FPP then see how i can do this.

from JSPM import FPP

print (FPP["Teachername"]) #output: Nitin Shivale

print (FPP["age"]) #Output: 36

print (FPP["Subjectname"]) #Output: Fundamentals of python programming


Module Search Path:

When we are importing the module in our program from where exactly it is located and gets loaded in our program is the next question comes to our mind.

Q. How the module search path works in the Python?

When you import module in your program for example, in our above example when we write import JSPM. 

What will happen where the python will search that module let's learn this first:

Python will search for the JSPM.py file from the following sources:

  • The current folder from which the program executes.
  • A list of folders specified in the PYTHONPATH environment variable, if you set it before.
  • An installation-dependent list of folders that you configured when you installed Python.

Python stores the resulting search path in the sys.path variable that comes from the sys module.

If we want to check how many paths are there inside sys.path variable, then we can check this by writing following code.

import sys

for path in sys.path:
    print(path)

To make sure Python can always find the module.py, you need to:

  • Keep module.py in the folder where the program will run.
  • Include the folder that contains the module.py in the PYTHONPATH environment variable. Or you can keep the module.py in one of the folders included in the PYTHONPATH variable.
  • Place the module.py in one of the installation-dependent folders.

Note:

>> import sys
>> sys.path.append('H:\\modules\\')

Python allows you to modify the module search path at runtime by modifying the sys.path variable. This allows you to store module files in any folder of your choice.

Since the sys.path is a list, you can append a search-path to it.


Q. What is Loading and Reloading of Module?

To load a module, we use the import statement. for e.g. to load JSPM module we write import JSPM

Why we have to reload module once it is loaded?
As we know there is always an improvement in every project's functionality likewise in our module also certain things are going to be added or changed after some times. 
To make available those newly added functionality to the code or program which one imported this module in it. we have to reload that module in once again in that program. 
Remember by using reload () function we can reload the module just you have to pass that module object name as an argument to reload () function.

For e.g. 

import sys
import JSPM
JSPM.reload(sys)

Q. What is dir () function?

In Python, the dir() function is a built-in function used to list the attributes (methods, properties, and other members like module, string, list, dictionaries, etc.) of an object.

Syntax: dir({object})

Parameter: dir([optional]): Here it takes object name

Returns:
dir() tries to return a valid list of attributes of the object it is called upon. Also, dir() function behaves rather differently with different type of objects, as it aims to produce the most relevant one, rather than the complete information. 


  • For Class Objects, it returns a list of names of all the valid attributes and base attributes as well. 
  • For Modules/Library objects, it tries to return a list of names of all the attributes, contained in that module. 
  • If no parameters are passed it returns a list of names in the current local scope.
Example:

# Python3 code to demonstrate dir()
# when no parameters are passed
# Note that we have not imported any modules
print(dir())
 
# Now let's import two modules
import sys
import math
 
print(dir())


Output
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '...

When User Defined Objects are Passed as Parameters

# Creation of a simple class with __dir()__
# method to demonstrate it's working
class jspmbsiotr:
 
    # Function __dir()___ which list all
    # the base attributes to be used.
    def __dir__(self):
        return ['college_name', 'principal',
               'intake', 'department', 'address']
 
 
# user-defined object of class jspmbsiotr
my_college = jspmbsiotr()
 
# listing out the dir() method
print(dir(my_college))


Output
['address', 'college_name', 'department', 'intake', 'principal']


Monday, 18 November 2024

Write a python program to accept a file name from the user and perform operations.


Q. What is Data Streaming and Buffering?

Data Streaming and Data Buffering is nothing but different methods of data transfer among client server architecture. As we know with HTTP Protocol, the client can either transfer data to the server that is uploading data to the server or sometimes client request some data from the server means downloading data from the server.


When the size of the data is more than some Megabytes to ensure the loss of data is minimal client and server can choose to transfer data in different chunks.


Now, when the server selects to send the data in chunks. so, at the time of download operations server chooses to transfer data in different chunks.

Now, when the client selects to send the data in chunks. so, at the time of uploading operations client choose to transfer data in different chunks.

Q. What is data Buffering?

Ans: When the requested data is completely accumulated inside the memory and then processed, we called it Buffering.


Q. What is Data Streaming?

Ans: when the data is processed at the time each chunk is received, we called it Streaming.

This is possible because request implements Readable Stream interface, and the content can be directly written to the file system using Writable Stream interface.

Q. What is File?

A File is collection of data that is stored on various devices like Computer, Laptop, Mobile and Servers.
We can say that file is the fundamental unit of digital storage which is used to Store, organize and manage data permanently on secondary storage.

Q. Why do we require File in python?

A File is collection of data that is stored on various devices like Computer, Laptop, Mobile and Servers. Now just consider the following scenario in python.

1. We write a python program to store employee information.
2. Accordingly, we write one class of employee.
3. We have created Three objects of employee inside the RAM (Random Access Memory) and store all the data inside it for three employees. but as you know RAM is a volatile memory that data is available till power is on.
4. Once power is off all data vanished from RAM and we loss all data completely.
5. Now every time when we want that data, we have to execute the code and create data inside the RAM.
6. What if we want that data permanently get stored inside secondary storage so that we can access it whenever we want. To accomplished these, we have to create a file and write all data inside that file for permanently storage.
7. Below is the scenario of Program RAM and File.


Q. How to create File in python?

By using python inbuilt function open (filename, mode) we can create file in python.



How many modes file gets open in python?

  1. r: open for read operation but file must be present.
  2. w: open already existed file if present and override the content in it. but if file is not already present in that case it can create new file and write in it.
  3. a: open already present file in append mode. in this mode we append content at the end.
  4. r+: To perform both operation (read and write data into the file). This mode does not override the already present data, but you can change the data starting from the beginning of the file.
  5. w+: To perform both operation (write and read data). It overwrites the previous file if it is already present, it will truncate the file to zero length or create a file if it does not exist.
  6. a+: To append and read data from the file. It will not override already present data.

Problem Statement:

Write a python program to accept a file name from the user and perform the following operations as       

1. Display the first N line of the file 
2.Find the frequency of occurrence of the word accepted from the user in the file





The number of functions used in above code and their usage are as follows:

1. Split () Function: If no character is specified in Split () function then by default it removes all the starting and ending whitespaces.

For Example:

Case 1:

msg = "  JSPM UNI  "

afterstriped = msg . strip ()

print(afterstriped)  # output is: "JSPM UNI"

Case 2:

msg = " ....,,,,nmsssss good sssrrt,,,...st"

afterstrip = msg . strip(".,nmsrt")

print(afterstrip) #output is: good