0% found this document useful (0 votes)
4 views39 pages

Unit - 5 (Python)

The document provides an overview of files, including their definitions, types (text and binary), and operations in Python. It explains how to open, read, write, and close files, along with methods for manipulating file content. Additionally, it covers file positions, format operators, and directory methods for managing files and directories.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views39 pages

Unit - 5 (Python)

The document provides an overview of files, including their definitions, types (text and binary), and operations in Python. It explains how to open, read, write, and close files, along with methods for manipulating file content. Additionally, it covers file positions, format operators, and directory methods for managing files and directories.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Files

Definition : File is a named location on the disk to store information.


File is used to store the information permanently.
1. Types of Files
There are two types of files
1. Text File
2. Binary File
1) Text File
• The text ASCII file is a simple file containing collection of characters that are readable to human.
• Various operations that can be performed on text files are - opening the file, reading the file, writing to
the file, appending data to the file.
• The text file deals with the text stream.
• In text file each line contains any number of characters include one or more characters including a
special character that denotes the end of file. Each line of the text have maximum 255 characters.
• When a data is written to the file, each newline character is converted to carriage return/ line feed
character. Similarly when data is read from the file, each carriage return feed character is converted to
newline character.
• Each line of data in the text file ends with newline character and each file ends with special character
called EOF (i.e. End of File) character.
2) Binary File
• Binary file is a file which contains data encoded in binary form.
• This data is mainly used for computer storage or for processing purpose.
• The binary data can be word processing documents, images, sound, spreadsheets, videos, or any other
executable programs.
• We can read text files easily as the contents of text file are ordinary strings but we can not easily read
the binary files as the contents are in encoded form.
• The text file can be processed sequentially while binary files can be processed sequentially or randomly
depending upon the need.
• Like text files, binary files also put EOF as an endmarker.
Difference between Text File and Binary File
Text File :
1. Data is present in the form of characters
2. The plain text is present in the file.
3. It can not be corrupted easily.
4. It can be opened and read using simple text editor like Notepad.
5. It have the extension such as py or .txt
Binary File
1. Data is present in the encoded form
2. The image, audio or text data can be present in the file.
3. Even if single bit is changed then the file gets corrupted.
4. It can not read using the text editor like Notepad.
5. It can have application defined extension,

2. Text Files
• The text files are type of files that store textual information.
• The text files are considered as persistent storages. That means once you store data in a text file that
remains in it even-if you shutdown and restart the computer. One can be picked up where they left off.
• Various operations that can be performed on text files are :
1. Open file
2. Close file
3. Writing to the file
4. Reading from file

• Opening a file
In python there is a built in function open() to open a file.
Syntax
File_object=open(file_name,mode)
Where File_object is used as a handle to the file.
Example
F = open("[Link]")
Here file named [Link] is opened and the file object is in variable F
• We can open the file in text mode or in binary mode. There are various modes of a file in which it is
opened. These are enlisted in the following table
Mode : Purpose
‘r’ - Open file for reading
‘w’ - Open file for writing. If the file is not created, then create new file and then write. If file is already
existing then truncate it.
‘x’ - Open a file for creation only. If the file already exists, the operation fails.
‘a’ - Open the file for appending mode. Append mode is a mode in which the data is inserted at the end of
existing text. A new file is created if it does not exist.
‘t’ - Opens the file in text mode
‘b’ - Opens the file in binary mode
‘+’ Opens a file for updation i.e. reading and writing.
For example :
Fo = open("[Link]", w) #opens a file in write mode
Fo = open("[Link]",rt) #Open a file for reading in text mode
• Closing a File
After performing all the file operations, it is necessary to close the file.
Closing of file is necessary because it frees all the resources that are associated with file.
Example –
fo = open("[Link]",rt)
[Link]() #closing a file.

3. Reading from Files


For reading the file , we must open the file in r mode and we must specify the correct file name which is
to be read
The read() method is used for reading the file. For example -

Let us close this file and reopen it. Then call read statement inside the print statement, illustrated as
follows –
Example 5.1.1 Write a Python program to read the contents of the file named '[Link]
Solution :
[Link]
inf = open('D:\\[Link]','rt')
print([Link]())
[Link]()
Output
Introduction to File operations.
Reading and Writing file operations in Python are easy to understand.
We enjoy it.
This line is written to file.
This is the last line of the file.
>>>
Note that a blank line is returned when the file reaches the end of the file.
There some other useful methods for reading the contents of the file. Let us discuss them with the help of
necessary illustrations
The readline() Method
The readline() method allows us to read a single line from the file. When file reaches to the end, it returns
an empty string.
Example 5.1.2 Write a Python program to read and display first two lines of the text file.
Solution :
[Link]
inf = open('D:\\[Link]','rt')
print([Link]())
print([Link]())
[Link]()

Program Explanation : In above program,


1) The file is opened using open statement.
2) The we call readline() statements inside two subsequent print statement. After reading from the file
using the readline() method, the control automatically passes to the next line. Hence we call readline()
inside the print statement again.
3) Finally we must not forget to close the file using close() method.
The readLines() Method
The readLines() method is used to print all the lines in the program. Following program illustrates it –
ReadLines [Link]
inf = open('D:\\[Link]','It')
print([Link]())
[Link]()
Output
Introduction to File operations.
Reading and Writing file operations in Python are easy to understand.
We enjoy it.
This line is written to file.
This is the last line of the file.
>>>
The list() Method
The list method is also used to display the contents of the file as a list. The program is as follows -
[Link]
inf = open('D:\\[Link]','rt')
print(list(inf))
[Link]()
Output

Note that we passed the file object as an argument to the list method.
Displaying File using Loop
This is the most commonly used method of reading the file. In this method the contents of the file are read
line by line using for loop.
Example 5.1.3 Write a program to display the contents of the file using for loop.
Solution :
[Link]
inf = open('D:\\[Link]', 'It')
for line in inf:
print(line)
[Link]()
Output
Introduction to File operations.
Reading and Writing file operations in Python are easy to understand.
We enjoy it.
This line is written to file.
This is the last line of the file.
>>>
Opening a file using with
We can open the file using keyword with. The advantage of this is that the file gets closed properly after
the read or write operations
OpenWith [Link]
with open('D:\\[Link]','rt') as inf:
for line in inf:
print(line)
[Link]()
Output
Introduction to File operations.
Reading and Writing file operations in Python are easy to understand.
We enjoy it.
This line is written to file.
This is the last line of the file.
>>> Example
5.1.4 Write a Python program to find the line that starts with the word "This" from the following text
which is stored in a file.
[Link]
This is a python program
python is superb.
This is third line of program
this python program is nice
Solution :
[Link]
fh = open('d:\\[Link]')
i=0
for line in fh:
line = [Link]()
if [Link]('This')= =-1:
continue
print(line)
Output
Example 5.1.5 Write a program in Python to split the text line written in the file into words.
Solution :
with open('d:\\[Link]', 'It') as inf:
line = [Link]()
word_list=[Link]()
print(word_list)
Output
['This', 'is', 'a', 'python', 'program')
>>>
4. Writing to Files
• For writing the contents to the file, we must open it in writing mode. Hence we use 'w' or 'a' or 'x' as a
file mode.
• The write method is used to write the contents to the file.
Syntax
File_object.write(contents)
• The write method returns number of bytes written.
• While using the 'w' mode in open, just be careful otherwise it will overwrite the already written contents.
Hence in the next subsequent write commands we use “\n” so that the contents are written on the next
lines in the file.
• For example:
The writelines() method
The writelines() method is used to write list of strings to the file. Following program illustrates this

Example 5.1.6 Write a python program to write multiple lines to a text file using writelines() method
Solution :
fo = open('d:\\[Link]','wt')
lines = ["Welcome to the Python programming\n","It is fun\n", "Python is easy\n", "But it is powerful
programming language"]
[Link](lines)
[Link]()
Output
Now open the Notepad and open the [Link] file in it. It will be something like this

Appending the file


Appending the file means inserting records at the end of the file.
For appending the file we must open the file in 'a' or 'ab' mode.
For example
fo = open('d:\\[Link]', 'a')
[Link]("Python has a wide scope in future")
[Link]()
Output
Just open the existing d: \[Link] file to check the contents. It will be as follows -
Example 5.1.7 : Write a python program to write n number of lines to the file and display all these lines
as output.
Solution :
print("How many lines you want to write")
n = int(input())
outFile = open("d:\\[Link]", "wt")
for i in range(n):
print("Enter line")
line = input()
[Link]("\n" + line)
[Link]()
print("\nThe Contents of the file '[Link]' are ...")
inFile = open("d:\\[Link]", "rt")
print([Link]())
[Link]()
Output

Example 5.1.8 Write a python program to write the contents in '[Link]' file. Read these contents and
write them to another file named '[Link]'
Solution :
print("How many lines you want to write")
n = int(input())
# Write data to first file ([Link])
outFile = open("d:\\[Link]", "wt")
for i in range(n):
print("Enter line")
line = input()
[Link](line + "\n")
[Link]()
# Open first file in read mode
inFile = open("d:\\[Link]", "rt")
# Open second file in write mode
outFile = open("d:\\[Link]", "wt")
# Copy contents from [Link] to [Link]
for i in range(n):
line = [Link]()
[Link](line)
[Link]()
[Link]()
# Display contents of second file
print("\nThe Contents of the file '[Link]' are ...")
inFile = open("d:\\[Link]", "rt")
print([Link]())
[Link]()
Example 5.1.9 How to Merge multiple files in to a new file using Python.
Solution :
one = two = ""
# Read first file
fp = open("d:\\[Link]", "rt")
one = [Link]()
[Link]()
# Read second file
fp = open("d:\\[Link]", "rt")
two = [Link]()
[Link]()
# Combine contents
one += "\n"
one += two
# Write into third file
fp = open("d:\\[Link]", "wt")
[Link](one)
[Link]()
print("Files merged successfully into [Link]")Output
Step 1: Create [Link] file using some text-editor like Notepad.

Step 2: Create [Link] file using some text-editor like Notepad.

Step 3: Now open the [Link] file using some text-editor. It will be as follows -

5. File Positions
The seek and tell method : The seek method is used to change the file position. Similarly the tell method
returns the current position.
The method seek() sets the file's current position at the offset.
Syntax
[Link](offsets, whence])
Where
• offset - This is the position of the read/write pointer within the file.
• whence - This is optional and defaults to o which means absolute file positioning, other values are 1
which means seek relative to the current position and 2 means seek relative to the file's end.
The method tell() returns the current position of the file read/write pointer within the file.
Syntax
[Link]()
Programming Example
inf = open('d:\\[Link]','rt')
print("\tThe contents of the file are...")
print([Link]())
print("\tThe current position is...")
print([Link]())#get current postion of file
[Link](0) #moves the file cursor to initial position
print("\tThe current position is...")
print([Link]())#get current position of file
Output

We can pass number of bytes to the seek method. These many bytes are skipped and then remaining
contents are displayed. For example
>>> [Link](10)
10
>>> print([Link]())
#note that 10 bytes are skipped and then the remaining contents are displayed
on to File Operations
Reading and writing operations in Python are easy
We enjoy it
This line is written in file
This is a last line of this file
>>>
6. Format Operator
• The format operator is specified using % operator.
• For example - if we want to display integer value then the format sequence must be %d, similarly if we
want to display string value then the format sequence must be %s and so on.
• Here is the illustration

• Various format specifiers are enlisted in the following table


Conversion : Meaning
d - Signed integer decimal.
i - Signed integer decimal.
u - Obsolete and equivalent to 'd', i.e. signed integer decimal.
x - Unsigned hexadecimal (lowercase),
X - Unsigned hexadecimal (uppercase).
e - Floating point exponential format (lowercase).
E - Floating point exponential format (uppercase).
f - Floating point decimal format.
F - Floating point decimal format.
g - Same as "e" if exponent is greater than - 4 or less than precision, "f" otherwise.
G - Same as "E" if exponent is greater than - 4 or less than precision, "F" otherwise,
c - Single character accepts integer or single character string).
r - String (converts any python object using repr()).
s - String (converts any python object using str()).
% - No argument is converted, results in a "%" character in the result.
• If there is more than one format sequence in the string, the second argument has to be a tuple. Each
format sequence is matched with an element of the tuple, in order.
• For example : Following errors are due to mismatch in tuple with format sequence.
>>> There are %d%d%d numbers'%(1,2) #mismatch in number of elements
TypeError : Not enough arguments for format string
>>> "There are %d rows'%'three'
TypeError: %d format: a number is required, not str #mismatch in type of element
Example 5.5.10 Write a python program to display the name of the student, his course and age.
Solution :
name = ‘Parth’
course = 'Computer Engineering'
age = 18
print("Name = %s and course= %s and age = %d"%(name,course,age))
print("Name = %s and course= %s and age = %d"%('Anand','Mechanical Engineering',21))
Output
Name = Parth and course= Computer Engineering and age = 18
Name = Anand and course= Mechanical Engineering and age = 21
>>>

7. Directory Methods
In this section we will discuss various directory methods.
1) Getting current working directory
For getting the name of current working directory we use the function named getcwd() method. This
method returns the name of current working directory. For example –
[Link]
import os
print([Link]())
Output
2) Displaying all the files and sub-directories inside a directory
For listing the contents of a directory we use the method listdir(). For example –
import os
print([Link]())
3) Creating a new directory
We can create a new directory using mkdir() method
[Link]
import os
[Link]("mypython Programs") #creates a folder named mypython Programs
print([Link]()) #displaying the directory contents
4) Removing the directory or a file
A file can be deleted using remove() method.
The rmdir() method removes an empty directory
For example
import os os
remove("[Link]") #removes file [Link]
print([Link]()) #displays the directory contents
[Link]("mypython Programs") #removes the directory named 'mypython
Programs' print([Link]())#displays the directory contents
5) Renaming a File
A file can be renamed using the rename() method.
The first parameter to this method is the old file name and second parameter is the new file name.
For example
import os
[Link]('d:\\[Link]','[Link]')
Review Questions
1. Tabulate different modes for opening a file and explain the same.
2. Explain about the file reading and writing operations using format operator with Python code.
3. Explain the commands used to read and write into a file with examples.
4. Discuss the use of format operator in file processing.
5. Write methods to rename and delete files.
Command Line Arguments
In python the sys module is used to use the command line arguments. There are three important steps to
be followed while accessing the command line arguments
1. Import the sys module
2. We can use [Link] for getting the list of command line arguments.
3. The len([Link]) gives total number of command line arguments.
The python program illustrating the access to command line arguments is as given below.
Step 1: Write a python script as follows. Here the name of the script file is [Link]

Step 2: The command prompt window is opened and type the python command at the prompt and we get
the output of the above program

Review Question
1. How to use command line arguments in Python.
Errors and Exceptions
Errors are normally referred as bugs in the program. They are almost always the fault of the programmer.
The process of finding and eliminating errors is called debugging.
There are mainly two types of errors :
1. Syntax errors: The python finds the syntax errors when it parses the source program. Once it find a
syntax error, the python will exit the program without running anything. Commonly occurring syntax
errors are :
(i) Putting a keyword at wrong place
(ii) Misspelling the keyword
(iii) Incorrect indentation
(iv) Forgetting the symbols such as comma, brackets, quotes
(v) Empty block
2. Run time errors : If a program is syntactically correct - that is, free of syntax errors – it will be run by
the python interpreter. However, the program may exit unexpectedly during execution if it encounters a
runtime error. The run-time errors are not detected while parsing the source program, but will occur due
to some logical mistake. Examples of runtime error are :
(i) Trying to access the a file which does not exists
(ii) Performing the operation of incompatible type elements
(iii) Using an identifier which is not defined
(iv) Division by zero Such type of errors are handled using exception handling mechanism.

1. Handling Exceptions
Definition of exception : An exception is an event which occurs during the execution of a program that
interrupts the normal flow of the program.
• In general, when a python script encounters a situation that it cannot cope with, it raises an exception.
• When a python script raises an exception, it must either handle the exception immediately otherwise it
terminates and quits.
• The exception handling mechanism using the try...except...else blocks.
• The suspicious code is placed in try block.
• After try block place the except block which handles the exception elegantly.
• If there is no exception then the else block statements get executed.
Syntax of try...except...else
try:
write the suspicious code here
except Exception 1:
If Exception 1 occurs then execute this code
except Exception 2:
If Exception 2 occurs then execute this code
else:
If there is no exception then execute this code.
Example
Suppose programmer wants some integer value and some character value is entered then python will raise
error. This scenario can be illustrated by following screenshot

Such situation can be gracefully handled using exception handling mechanism as follows:
Step 1: Create a python script as follows:

Step 2: Now run the above code for both valid and invalid inputs.
Output(Run1: Execution of except block)
• A single try can have multiple except statements. We can specify standard exception names for handling
specific type of exception. For example Example
5.3.1 : Write a python program to perform division of two numbers. Raise the exception if the wrong
input(other than integer) is entered by the user. Also raise an exception when divide by zero occurs,
Solution :
try:
a = int(input("Enter value of a: "))
b = int(input("Enter value of b: "))
c=a/b
except ValueError:
print("You have entered wrong data")
except ZeroDivisionError:
print("Divide by Zero Error!!!")
else:
print("The result:", c)
Output(Run1) Output(Run2) Output(Run3)
Example 5.3.2 Write a program to read th contents of the file. If the file does not exist then raise
appropriate exception.
Solution :
try :
inFile = open(“[Link]”,’rt’)
except IOError:
print(“Error;File Not found”)
else;
print([Link]()) # displaying contents of file on getting file
Output
Example 5.3.3 : Write a python program to open a file having no write permission but trying to write the
data. Handle this situation using exception handling mechanism.
Solution :
try:
FileObj = open("[Link]","rt')
[Link]("This is my data")
except IOError:
print("Error:File does not have write permission!!!")
else:
print("Contents are written Successfully!!!")
Output

Standard Exceptions in Python


Name : Pur Purpose
1. Exception - Base class for all exceptions
2. ArithmeticError - Base class for all errors that occur for numeric calculation.
3. OverflowError - Raised when a calculation exceeds maximum limit for a numeric type.
4. Floating PointError - Raised when a floating point calculation fails.
5. ZeroDivisionError - Raised when division or modulo by zero takes place for all numeric types.
6. EOFError - Raised when there is no input from either the raw_input() or input() function and the end of
file is reached.
7. ImportError - Raised when an import statement fails.
8. KeyboardInterrupt Raised when the user interrupts program execution, usually by pressing Ctrl+c.
9. NameError - Raised when an identifier is not found in the local or global namespace.
10. IOError - Raised when an input/ output operation fails.
11. SystemError - Raised when the interpreter finds an internal problem, but when this error is
encountered the python interpreter does not exit.
12. SystemExit - Raised when python interpreter is quit by using the [Link]() function. If not handled in
the code, causes the interpreter to exit.
13. TypeError - Raised when an operation or function is attempted that is invalid for the specified data
type.
14. ValueError - Raised when the built-in function for a data type has the valid type of arguments, but the
arguments have invalid values specified.
15. RuntimeError - Raised when a generated error does not fall into any category.
Use of finally
The finally clause will be executed at the end of the try-except block no matter what - if there is no
exception, if an exception is raised and handled, if an exception is raised and not handled, and even if we
exit the block using break, continue or return. We can use the finally clause for cleanup code that we
always want to be executed.
For example :
try:
age = int(input("Enter your age: "))
except ValueError:
print("Invalid age")
else:
print("Your age is:", age)
finally:
print("Good Bye")
Output(Run1) Output(Run2)

Review Questions
1. Appraise use of try block and except block in Python with syntax.
2. Describe how exceptions are handled in Python with necessary examples.
3. What are exceptions ? Explain the methods to handle them with example.
Modules
• There some standard functionalities in python that are written in particular module. For using those
functionalities, it is essential to import the corresponding module first.
• For example : There are various functionalities available under the module math. For instance, if you
want to find out the square root of some number then you need to import module math first and then use
the sqrt function.
• Following screenshot illustrates this idea :

• Basically modules in python are .py files in which set of functions are written.
• Modules are imported using import command.

1. The from... import Statement


• There are many variables and functions present in the module. We can use them by using the import
statement.
• When we simply use import statement, then we can use any variable or function present within that
module.
• When we use from...import statement, then we can use only selected variables or functions present
within that module.
For example
from math import sqrt
print("Square root(25) = ",sqrt(25))
Output
• If we want to use some different name for the standard function present in the module, then we can use
as keyword. Following code illustrates this -
[Link]
from math import sqrt as my_sq_root
print("Square root(25)= "my_sq_root(25))
Output
Square root(25) = 5.0
>>>
2. Name of the Module
• Every module has a name. One can use the name of the module using ___name__ attribute of the
module. For example
[Link]
print("Welcome")
print("Name of this module is:",_name_)
Output

The _name__ is a built-in variable that is set when the program starts. If the program is running as a
script, _name__ has the value'_main__
For every standalone program written by the user the module is always __main__. Hence is the output.
3. Creating a Module
• We can create our own module. Every Python program is a module. That means every file that we save
using .py extension is a module.
• Following are the steps that illustrates how to create a module –
Step 1 : Create a file having extension .py. Here we have created a file [Link]. In this file, the
function fun is defined.
[Link]
def fun(usr):
print("Welcome ",usr)
Step 2 : Now open the python shell and import the above module and then call the functionality present
in that module.
Output

Step 3: We can also call the above created PrintMsg module in some another file. For that purpose, open
some another file and write the code in it as follows –
[Link]
import PrintMsg #importing the user defined module
[Link]("Rupali") #calling the function present in that module
Step 4: Now run the [Link] program and you will get the output as follows –
Example 5.4.1 Write a module for displaying the Fibonacci series.
Solution:
Step 1 :
[Link]
def fib(n): # write Fibonacci series up to n
a, b = 0,1
while b < n:
print(b, end='')
a, b = b, a + b
print()
Step 2: Open the python shell and import the above module and access the functionality within it. The
output will be as follows:

Example 5.4.2 Write a Python program to define a module for swapping the two values. Then write a
driver program that will call the function defined in your swap module.
Solution :
Step 1: Create a module in a file and write a function for swapping the two values. The code is as follows
[Link]
def Swap(a,b):
tempr a = b
b = temp
print("After Swapping")
print(a)
print(b)
Save and Run the above code.
Step 2: Now create a driver program that will invoke the swap function created in above module.
[Link]
import swapProg
print("Swap(10,20)")
[Link](10,20)
print("Swap('a','b')")
swapProg. Swap('a','b')
Step 3: Save and run the above code. The output will be as follows –

4. The dir() Function


The dir() function is an inbuilt function. It is used display functions, variables or classes used in the
module.
Following code shows the use of dir() function in the module.
MyModule [Link]
def display(usr):
print(usr)
usr = "Admin"
display(usr)
print(dir())
Output

5. Python Module
• Python module is basically a file containing some functions and statements.
• When Python file is executed directly it is considered as main module.
• The main module is recognized as __main__ and provide the basis for a complete Python program.
• The main module can import any number of other modules. But main module can not be imported into
some other module.
6. Modules and Namespace
• Namespace is basically a collection of different names. Different namespaces can time but are
completely isolated.
• If two names(variables) are same and are present in the same scope then it will cause name clash. To
avoid such situation we use the keyword namespace.
• In Python each module has its own namespace. This namespace includes all the names of its function
and variables.
• If we use two functions having same name belonging to two different modules at a time in some other
module then that might create name clash. For instance –
Step 1 : Create first module for addition functionality.
[Link]
def display(a,b):
return a + b
Step 2: Create second module for multiplication functionality.
[Link]
def display(a,b):
return a*b
Step 3: If we call above modules in our driver program for performing both addition and multiplication,
then we get error because of name clash for the function.
[Link]
import FirstModule
import SecondModule
print(display(10,20))
print(display(5,4))
Step 4: To resolve this ambiguity we should call these functionalities using their module names. It is
illustrated as follows -
import FirstModule
import SecondModule
print([Link](10,20))
print([Link](5,4))
Output
30
20
7. Global, Local and Built-in Namespace
• There are three commonly used categories of namespaces - Global namespace, local namespace, and
built-in namespace.
• The global namespace contains the module which is currently executing. The local namespace is a
namespace for defining the names in a local function. The built-in namespace is a namespace in which the
built in functionality can be invoked.
Following Python code represents all these namespaces.
import math
def even_number(number): #global namespace
num = number #local namespace
if(num%2 = = 0);
return num
else:
return 0
print("Enter some number")
num=int(input())
if(even_number(num)!=0):
print("The square root of",num,"is ",[Link](num)) #built-in namespace
8. Private Variable
• All the identifiers defined in the module are public. That means the identifier defined in one module can
be invoked by other module without any restriction. ‘
• But there are private variables. The variables that begin with two underscore (1) are called private
variable. These are the variables which are used only within that module. Other module cannot access
these private variables.
• Even-if we write import * from modulename then all the identifiers except the private variables can be
imported.
Review Questions
1. What is a module ? Give example.
2. What are modules in Python ? How will you import them ? Explain the concept by creating and
importing a module.
Packages
• Packages are namespaces which contain multiple packages and modules. They are simply directories.
• Along with packages and modules the package contains a file named __init_ _.py. In fact to be a
package, there must be a file called __init_ _.py in the folder.
• Packages can be nested to any depth, provided that the corresponding directories contain their own
_init__.py file.
• The arrangement of packages is as shown in Fig. 5.5.1.

For example :
We can access the package and various subpackages and modules in it as follows:
import My_Package #loads My_Package/ _init__.py
import My_Package.module1 #loads My_Package/[Link]
from My_Package import module2
import My_Package.SubPackage1
When we import Main package then there is no need to import subpackage. For example
import My_Package My_Package.
SubPackage1.my_function1( )
• Thus we need not have to import SubPackage1.
• The primary use of __init__.py is to initialize Python packages. Simply putting the subdirectories and
modules inside a directory does not make a directory a package, what it needs is a __init_.py inside it.
Then only Python treats that directory as package.
How to Create a Package?
• To understand how to create a package, let us take an example. We will perform arithmetic operations
addition, multiplication, division and subtraction operations by creating a package. Just follow the given
steps to create a package.
Step 1: Create a folder named MyMaths in your working drive. I have created it on D:drive.
Step 2: Inside MyMaths directory create _init_.py file. Just create an empty file.
Step 3: Create a folder named Add inside MyMaths. Inside Add folder create file named [Link].
The [Link] will be as follows
[Link]
def add_fun(a,b):
return a + b
Step 4: Similarly the folder Sub insider MyMaths is created. Inside which create a file [Link].
The code for this file is
[Link]
def sub_fun(a,b):
return(a-b)
Step 5: Similarly the folder Mul insider MyMaths is created. Inside which create a
file [Link]. The code for this file is
[Link]
def mul_fun(a,b):
return(a*b)
Step 6: Similarly the folder Div insider MyMaths is created. Inside which create a file [Link]. The
code for this file is
[Link]
def div_fun(a,b):
return (a/b)
Step 7: The overall directory Structure will be as given below. Note that _pycache_is automatically
generated directory.
Step 8: Now on the D: drive create a driver program which will invoke all the above functionalities
present in the MyMaths package. I have named this driver program as testing_arithmetic.py. It is as
follows

print("The addition of 10 and 20 is: ",[Link].add_fun(10,20))


print("The multiplication of 10 and 20 is: ",[Link].mul_fun(10,20))
print("The division of 10 and 5 is: ",[Link].div_fun(10,5))
print("The subtraction of 20 and 10 is: ",[Link].sub_fun(20,10))
Step 9: Now just run this testing program and you will get following output
Output
The addition of 10 and 20 is:30
The multiplication of 10 and 20 is:200
Illustrative Programs

1. Word Count
This program counts the number of words present in the given file. If the specified file is not present, then
exception is raised.
Step 1:
try:
inFile = open("D:\\[Link]", "rt")
except:
print("Error: File not found")
else:
data = [Link]()
words = [Link]()
print(words)
print('-' * 80)
print("Total number of words are", len(words))
print('-' * 80)
[Link]()
Step 2:
The input file used for reading and for word counting is as follows

Step 3:
The output for the Python program created in Step 1 is as follows –
2. Copy File
In this program, the contents of one file are copied line by line to another file. For that purpose I have
created a file named [Link] in which some contents are stored. These contents are copied to another file
named [Link]. The python program for this is as given below -
Step 1: The python program is as follows –
print("\tProgram for Copying the File")
with open("d:\\[Link]", "r") as inFile:
with open("d:\\[Link]", "w") as outFile:
for line in inFile:
[Link](line)
print("\nThe contents of original File are...\n")
with open("d:\\[Link]", "r") as inFile:
print([Link]())
print("\nThe contents of copied File are...\n")
with open("d:\\[Link]", "r") as inFile:
print([Link]())
Step 2: The input file [Link] is as follows –
[Link]

Step 3: The output of the python program created in step 1 is as follows -


3. Voter's Age Validation
Python Program
try:
age = int(input("Enter your age: "))
if age > 18:
print("Eligible to vote!!!")
else:
print("Not eligible to vote!!!")
except ValueError as err:
print(err)
finally:
# code to be executed whether exception occurs or not
#typically for closing files and other resources
print("Good Bye!!!")
Output(Run 1)
Enter your age: 20
Eligible to vote!!!
Good Bye!!!
>>>
Output(Run 2)
Enter your age: twenty
invalid literal for int() with base 10: 'twenty'
Good Bye!!!
>>>

4. Marks Range Validation (0-100)


Python Program
while True :
try:
num = int(input("Enter a number between 1 and 100: "))
if num in range(1,100):
print("Valid number!!!")
break
else :
print("Invalid number. Try again.")
except :
print("That is not a number. Try again.")
Output
Enter a number between 1 and 100: -1
Invalid number. Try again.
Enter a number between 1 and 100-10000
Invalid number. Try again.
Enter a number between 1 and 100- five
This not a number . Try again
Enter a number between 1 and 100: 99
Valid number
>>>
Review Question
1. Design a Python code to count the number of words in a Python file.

You might also like