Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
77 views

Python Notes - 4

The document discusses Python modules, packages, and file input/output (I/O). It explains how to define modules, import modules from packages using dot notation, and organize related modules into packages with an __init__.py file. It also covers opening, reading, writing, and closing files in Python along with various file I/O methods like read(), write(), seek(), and tell().

Uploaded by

Prasad S R
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views

Python Notes - 4

The document discusses Python modules, packages, and file input/output (I/O). It explains how to define modules, import modules from packages using dot notation, and organize related modules into packages with an __init__.py file. It also covers opening, reading, writing, and closing files in Python along with various file I/O methods like read(), write(), seek(), and tell().

Uploaded by

Prasad S R
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Creating Module

Type the following and save it as “example.py”


# Python Module example
def add(a, b):
result = a + b
return result
we have defined a function add() inside a module named example. The function takes in two numbers and returns their sum.
How to import modules
 We can import the definitions inside a module to another module or the interactive interpreter in Python.
 We use the import keyword to do this. To import our previously defined module example, we type the following in the Python prompt.
>>> import example
 This does not import the names of the functions defined in example directly in the current symbol table. It only imports the module name example there.
 Using the module name we can access the function using the dot . operator. For example:
>>> example.add(4,5.5)
RESULT : 9.5
Packages

 we may keep all the songs in the "music" directory(folder).


 Python has packages for directories and modules for files.

As our application program grows larger in size with a lot of modules, we place similar modules in one
package and different modules in different packages.
This makes a project (program) easy to manage and conceptually clear.
Directory(folder) can contain subdirectories and files, a Python package can have sub-packages and modules.
A directory must contain a file named  __init__.py  in order for Python to consider it as a package. This file can
be left empty but we generally place the initialization code for that package in this file.
Example
we are developing a game. One possible organization of packages and modules could be as shown in the figure
below.

Importing module from a package


We can import modules from packages using the dot (.) operator.
Syntax: import <packagename>.<modulename>
 
For example, if we want to import the start module in the above example, it can be done as follows:
import Game.Level.start
Now, if this module contains a function named  select_difficulty() , we must use the full name to reference it.
Game.Level.start.select_difficulty(2)
If this construct seems lengthy, we can import the module without the package prefix as follows:
from Game.Level import start
We can now call the function simply as follows:
start.select_difficulty(2)
Another way of importing just the required function (or class or variable) from a module within a package would be as
follows:
from Game.Level.start import select_difficulty
Now we can directly call this function.
select_difficulty(2)
Although easier, this method is not recommended. Using the full namespace avoids confusion and prevents two same
identifier names from colliding.
While importing packages, Python looks in the list of directories defined in  sys.path , similar as for module search
path.
CREATING user PACKAGE for below structure
Provision_Shop (folder) (package)
Soap(module1)
Santoor (function)
My name is Santoor cost is Rs:45
Lux (function)
My name is Lux cost is Rs:55
Chintol (function)
My name is Chintol cost is Rs:65

Paste (module)
Colgate (function)
My name is Colgate cost is Rs:100
Pepsodent (function)
My name is Pepsodent cost is Rs:150
Closeup (function)
My name is Closeup cost is Rs:200
Step 1: we need to create a Folder(directory) in the python path C:\Program Files\Python39\Lib
( we are creating folder Provision_Shop in above path)
Step 2: with that folder we need to create required modules…
(we are ceating module1 Soap.py with functions of Santoor, Lux, Chintol)
(we are ceating module2 Paste.py with functions of Colgate, Pepsodent, Closeup)
Step 3: Create a __init__.py file with the Provision_Shop folder
from Provision_Shop.Soap import *
from Provision_Shop.Paste import *
Santoor()
Lux()
Chintol()
Colgate()
Python Dictionary
Python dictionary is an unordered collection of items. Each item of a dictionary has a key/value pair.
Dictionaries are optimized to retrieve values when the key is known.
Creating Python Dictionary
 Creating a dictionary is as simple as placing items inside curly braces {} separated by commas.
 An item has a key and a corresponding value that is expressed as a pair (key: value).
 While the values can be of any data type and can repeat, keys must be of immutable type (string, number or tuple with
immutable elements) and must be unique.

# empty dictionary
my_dict = {}

# dictionary with integer keys


my_dict = {1: 'apple', 2: 'ball'}

# dictionary with mixed keys


my_dict = {'name': 'John', 1: [2, 4, 3]}

# using dict()
my_dict = dict({1:'apple', 2:'ball'})
Accessing Elements from Dictionary
get()  method.
# get vs [] for retrieving elements
my_dict = {'name': 'Jack', 'age': 26} print(my_dict.get('address')) error as none
print(my_dict['name']) print(my_dict['address']) error
print(my_dict.get('age'))
Changing and Adding Dictionary elements
# Changing and adding Dictionary Elements #Output: {'age': 27, 'name': 'Jack'}
my_dict = {'name': 'Jack', 'age': 26} print(my_dict)
print(my_dict)
# add item
# update value my_dict['address'] = 'Downtown'
my_dict['age'] = 27
# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}
print(my_dict)
Removing elements from Dictionary
We can remove a particular item in a dictionary by using the pop() method. This method removes an item with the
provided key and returns the value
# Removing elements from a dictionary # Output: {1: 1, 2: 4, 3: 9}
print(squares)
# create a dictionary
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} # remove all items
squares.clear()
# remove a particular item, returns its value
# Output: 16 # Output: {}
print(squares.pop(4)) print(squares)

# Output: {1: 1, 2: 4, 3: 9, 5: 25} # delete the dictionary itself


print(squares) del squares
Python File I/O( Input and Output )
Files are named locations on disk to store related information. They are used to permanently store data in a non-volatile memory
(e.g. hard disk).
When we want to read from or write to a file, we need to open it first. When we are done, it needs to be closed so that the resources
that are tied with the file are freed.
Hence, in Python, a file operation takes place in the following order:
1. Open a file
2. Read or write (perform operation)
3. Close the file
Opening Files in Python
Python has a built-in open() function to open a file. This function returns a file object, also called a handle, as it is used to read or
modify the file accordingly.
>>> f = open("test.txt") # open file in current directory
>>> f = open("C:/Python38/README.txt") # specifying full path

We can specify the mode while opening a file. In mode, we specify whether we want to read  r, write  w  or append  a  to the file.
The default is reading in text mode. In this mode, we get strings when reading from the file.
f = open("test.txt",’r’) # equivalent to 'r' or 'rt'
f = open("test.txt",'w') # write in text mode
f = open("img.bmp",'r+b') # read and write in binary mode
 
Moreover, the default encoding is platform dependent. In windows, it is  cp1252 but  utf-8  in Linux.
f = open("test.txt", mode='r', encoding='utf-8')

Closing Files in Python


Closing a file will free up the resources that were tied with the file. It is done using the  close()  method available in Python.
f = open("test.txt", encoding = 'utf-8')
# perform file operations
f.close()

Writing to Files in Python


In order to write into a file in Python, we need to open it in write  w , append  a  or exclusive creation  x  mode.
We need to be careful with the w mode, as it will overwrite into the file if it already exists. Due to this, all the previous data are
erased.
Writing a string or sequence of bytes (for binary files) is done using the write() method. 
with open("test.txt",'w',encoding = 'utf-8') as f:
f.write("my first file\n")
f.write("This file\n\n")
f.write("contains three lines\n")
This program will create a new file named test.txt  in the current directory if it does not exist. If it does exist, it is overwritten.

Reading Files in Python


To read a file in Python, we must open the file in reading  r  mode.
There are various methods available for this purpose.
We can use the  read(size)  method to read in the size number of data. If the size parameter is not specified, it reads and returns
up to the end of the file.
>>> f = open("test.txt",'r',encoding = 'utf-8')
>>> f.read(4) # read the first 4 data
'This'

>>> f.read(4) # read the next 4 data


' is '

>>> f.read() # read in the rest till end of file


'my first file\nThis file\ncontains three lines\n'

>>> f.read() # further reading returns empty sting


''
We can see that the read() method returns a newline as '\n'. Once the end of the file is reached, we get an empty string on further
reading.

We can change our current file cursor (position) using the seek() method. Similarly, the tell() method returns our current position
(in number of bytes).
>>> f.tell() # get the current file position
56

>>> f.seek(0) # bring file cursor to initial position


0

>>> print(f.read()) # read the entire file


This is my first file
This file
contains three lines

We can read a file line-by-line using a for loop. This is both efficient and fast.
>>> for line in f:
... print(line, end = '')
...
This is my first file
This file
contains three lines
we can use the f.tell() method to read individual lines of a file. This method reads a file till the newline, including the newline
character.
>>> f.readline()
'This is my first file\n'

>>> f.readline()
'This file\n'

>>> f.readline()
'contains three lines\n'

>>> f.readline()
''
the readlines() method returns a list of remaining lines of the entire file. All these reading methods return empty values when the
end of file (EOF) is reached.
>>> f.readlines()
['This is my first file\n', 'This file\n', 'contains three lines\n']
Method Description

close() Closes an opened file. It has no effect if the file is already closed.

detach() Separates the underlying binary buffer from the TextIOBase and returns it.

fileno() Returns an integer number (file descriptor) of the file.

flush() Flushes the write buffer of the file stream.

isatty() Returns True if the file stream is interactive.

read(n) Reads at most n characters from the file. Reads till end of file if it is negative or None.

readable() Returns True if the file stream can be read from.

readline(n=-1) Reads and returns one line from the file. Reads in at most n bytes if specified.

readlines(n=-1) Reads and returns a list of lines from the file. Reads in at most n bytes/characters if specified.

seek(offset,from=SEEK_SET) Changes the file position to offset bytes, in reference to from (start, current, end).

seekable() Returns True if the file stream supports random access.

tell() Returns the current file location.

truncate(size=None) Resizes the file stream to size bytes. If size is not specified, resizes to current location.

writable() Returns True if the file stream can be written to.


write(s) Writes the string s to the file and returns the number of characters written.

writelines(lines) Writes a list of lines to the file.


Object Oriented Programming
Python is a multi-paradigm programming language. It supports different programming approaches.
One of the popular approaches to solve a programming problem is by creating objects. This is known as Object-
Oriented Programming (OOP).
An object has two characteristics:
 attributes
 behavior
Class
A class is a blueprint for the object.
class Parrot:
Object
An object (instance) is an instantiation of a class. When class is defined, only the description for the object is
defined. Therefore, no memory or storage is allocated.
obj = Parrot()
Here, obj is an object of class Parrot.
# A Sample class
class Student:
pass

stu1=Student()
stu1.name="AAA"
stu1.marks=30
print(stu1.name)
print(stu1.marks)

stu2=Student()
stu2.name="BBB"
stu2.marks=50
print(stu2.name)
print(stu2.marks)

# A Sample class with method


class Student:
def chkres(self):
if self.marks>40:
return "Pass"
else:
return "Fail"
stu1=Student()
stu1.name="AAA"
stu1.marks=30
res=stu1.chkres()
print(res)

# A Sample class with __init__ method


class Student:
def chkres(self):
if self.marks>40:
return "Pass"
else:
return "Fail"
def __init__(self,name,marks):
self.name=name
self.marks=marks

stu1=Student("AAA",50)
res=stu1.chkres()
print(res)
Inheritance
Inheritance is a way of creating a new class for using details of an existing class without modifying it. The newly
formed class is a derived class (or child class). Similarly, the existing class is a base class (or parent class).

class Voting:
def chkvoting(self):
if self.age>18:
return "Eligible for Voting"
else:
return "Not Eligible for Voting"

class Student(Voting):
def chkres(self):
if self.marks>40:
return "Pass"
else:
return "Fail"
def __init__(self,name,age,marks):
self.name=name
self.age=age
self.marks=marks

stu1=Student("AAA",15,50)
res=stu1.chkres()
print(res)
vot=stu1.chkvoting()
print(vot)

Encapsulation
Using OOP in Python, we can restrict access to methods and variables. This prevents data from direct
modification which is called encapsulation.
class Computer:
x=5000

def __init__(self):
self.maxprice = 900

def setMaxPrice(self, price):


self.maxprice = price

c = Computer()
print("X value for C:",c.x)
print("Selling Price",c.maxprice)

# change the price


c.maxprice = 1000
print("Selling Price",c.maxprice)

# using setter function


c.setMaxPrice(2000)
print("Selling Price",c.maxprice)

Polymorphism
Polymorphism is an ability (in OOP) to use a common interface for multiple forms (data types).
class Parrot:

def fly(self):
print("Parrot can fly")

def swim(self):
print("Parrot can't swim")

class Penguin:

def fly(self):
print("Penguin can't fly")

def swim(self):
print("Penguin can swim")
# common interface
def flying_test(bird):
bird.fly()

#instantiate objects
blu = Parrot()
peggy = Penguin()

# passing the object


flying_test(blu)
flying_test(peggy)

You might also like