Py Unit - 5
Py Unit - 5
1 Files
Most of the programs we have seen so far are transient in the sense that
they run for a short time and produce some output, but when they end, their data
disappears. If you run the program again, it starts with a clean slate.
Other programs are persistent: they run for a long time (or all the time); they
keep at least some of their data in permanent storage (a hard drive, for example);
and if they shut down and restart, they pick up where they left off.
One of the simplest ways for programs to maintain their data is by reading and
writing text files. An alternative is to store the state of the program in a database.
5.1.1 Text Files
A text file is a sequence of characters stored on a permanent medium like a
hard drive, flash memory, or CD-ROM. Text file contain only text, and has no special
formatting such as bold text, italic text, images, etc. Text files are identified with the
.txt file extension.
5.1.2 Reading and Writing to Text Files
Python provides inbuilt functions for creating, writing and reading files. There
are two types of files that can be handled in python, normal text files and binary files
(written in binary language,0s and 1s).
££ Text files : In this type of file, each line of text is terminated with a special
character called EOL (End of Line), which is the new line character ( \n‘)
in python by default.
££ Binary files : In this type of file, there is no terminator for a line and
the data is stored after converting it into machine understandable binary
language.
5. 2 Problem Solving and Python Programming
Syntax:
File_object = open(r”File_Name”,”Access_Mode”)
The file should exist in the same directory as the python program file else,
full address (path will be discussed in later section of this unit) of the file should
be written on place of filename. Note: The r is placed before filename to prevent
the characters in filename string to be treated as special character. For example, if
there is \temp in the file address, then\t is treated as the tab character and error is
raised of invalid address. The r makes the string raw, that is, it tells that the string
is without any special characters. The r can be ignored if the file is in same directory
and address is not being placed.
Example:
>>> f1 = open(“sample.txt”,”a”)
>>> f2 = open(r”G:\class\python\sample3.txt”,”w+”)
Example:
>>> f1 = open(“smapl.txt”,”a”)
>>>f1.close()
After closing a file we can‘t perform any operation on that file. If want to do so,
we have to open the file again.
5.1.5 Reading from a File
To read the content of a file, we must open the file in reading mode. There are
three ways to read data from a text file.
5. 4 Problem Solving and Python Programming
3. readlines() : Reads all the lines and return them as each line a string
element in a list.
File_object.readlines()
Example
Consider the content of file sample.txt that is present in location G:\class\
python\code\ as
Read Only
Read and Write
Write OnlyWrite and Read
Append Only
Append and Read
Here \n denotes next line character. If you again run the same script, you will
get empty string. Because during the first read statement itself file handler reach
the end of the file. If you read again it will return empty string
>>>f1.read()
‘’
So in order to take back the file handler to the beginning of the file you have
to open the file again or use seek() function. We will discuss about seek function in
upcoming section.
Files , Modules and Packages 5.5
>>> f1=open(“G:\class\python\code\sample.txt”,”r”)
>>>f1.read(10)
‘Read Only\n’
>>> f1=open(“G:\class\python\code\sample.txt”,”r”)
>>>f1.readline()
‘Read Only\n’
>>> f1=open(“G:\class\python\code\sample.txt”,”r”)
>>>f1.readlines()
[‘Read Only\n’, ‘Read and Write\n’, ‘Write Only\n’, ‘Write and Read\n’,
‘Append Only\n’, ‘Append and Read’]’
>>> f1=open(“G:\class\python\code\sample.txt”,”r”)
>>>f1.tell()
0L
>>>f1.readline()
‘Read Only\n’
>>>f1.tell()
11L
5. 6 Problem Solving and Python Programming
>>>f1.seek(0)
>>>f1.tell()
0L
>>>f1.seek(5)
>>>f1.tell()
5L
>>>f1.readline()
‘Only\n’
Example:
>>> f4=open(“fruit.txt”,”w”)
>>>fruit_list=[‘Apple\n’,’Orange\n’,’Pineapple\n’]
>>>f4.writelines(fruit_list)
>>>f4.write(‘Strawberry\n’)
>>>f4.close()
>>> f4=open(“fruit.txt”,”r”)
>>>f4.read() ‘Apple\nOrange\nPineapple\nStrawberry\n’
Example:
>>> f4=open(‘fruit.txt’,’a’)
>>>f4.write(‘Banana’)
>>>f4.close()
>>> f4=open(‘fruit.txt’,’r’)
>>>f4.read()
‘Apple\nOrange\nPineapple\nStrawberry\nBanana\n’
>>> run=8
>>> ‘%d’%run
‘8’
The result is the string ‘8’, which is not to be confused with the integer value
8.Some other format strings are.
Conversion Meaning
o Unsigned octal.
u Unsigned decimal.
A format sequence can appear anywhere in the string, so you can embed a
value in a sentence:
>>> ‘India need %d runs’%3
‘India need 3 runs’
Files , Modules and Packages 5.9
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.
>>> ‘India need %d runs in %d balls’%(3,5)
‘India need 3 runs in 5 balls’
The following example uses ‘%d’ to format an integer, ‘%g’ to format a floating-
point number, and ‘%s’ to format a string:
>>> ‘%d %s price is %g rupees’%(5,’apple’,180.50)
‘5 apple price is 180.500000 rupees’
The number of elements in the tuple has to match the number of format
sequences in the string. Also, the types of the elements have to match the format
sequences:
>>> ‘%d %d %d’ % (1, 2)
TypeError: not enough arguments for format string
>>> ‘%d’ % ‘apple’
TypeError: %d format: a number is required, not str
In the first example, there aren‘t enough elements; in the second, the element
is the wrong type.
5.1.11 Filenames and Paths
Files are organized into directories (also called ‖folders ). Every running
program has a ‖current directory , which is the default directory for most
operations. For example, when you open a file for reading, Python looks for it in the
current directory.
The os module provides functions for working with files and directories (-os
stands for -operating system ). os.getcwd returns the name of the current directory:
>>> import os
>>>os.getcwd()
‘C:\\Python27’
cwd stands for -current working directory . A string like ‘C:\\Python27’ that
identifies a file or directory is called a path.
5. 10 Problem Solving and Python Programming
A path that begins with drive letter does not depend on the current directory;
it is called an absolute path. To find the absolute path to a file, you can use os.path.
abspath:
os.path provides other functions for working with filenames and paths. For
example, os.path.exists checks whether a file or directory exists:
>>>os.path.exists(‘memo.txt’)
True
>>>def walk(dirname):
for name in os.listdir(dirname):
path = os.path.join(dirname, name)
ifos.path.isfile(path):
print(path)
else:
walk(path)
>>>cwd=os.getcwd()
>>>walk(cwd)
Output
C:\Python27\DLLs\bz2.pyd
C:\Python27\DLLs\py.ico
C:\Python27\DLLs\pyc.ico
C:\Python27\DLLs\pyexpat.pyd
C:\Python27\DLLs\select.pyd
C:\Python27\DLLs\sqlite3.dll
C:\Python27\DLLs\tcl85.dll
C:\Python27\include\abstract.h
C:\Python27\include\asdl.h
C:\Python27\include\ast.h
os.path.join takes a directory and a file name and joins them into a complete
path.
>>>os.path.join(cwd,’stringsample.txt’)
‘C:\\Python27\\stringsample.txt’
The command line arguments are handled using sys module. We can access
command-line arguments via the sys.argv. This serves two purposes “
££ sys.argv is the list of command-line arguments.
££ len(sys.argv) is the number of command-line arguments.
Here sys.argv[0] is the program nameie. script name.
Example : 1
Consider the following script command_line.py
import sys
print ‘There are %d arguments’%len(sys.argv)
print ‘Argument are’, str(sys.argv)
print ‘File Name is: ‘, sys.argv[0]
Program
import sys
source=open(sys.argv[1],’r’)
destination=open(sys.argv[2],’w’)
while(True):
new_line=source.readline()
ifnew_line==’’:
break
destination.write(new_line)
source.close()
destination.close()
Now run above script as follows – in Command prompt:
C:\Python27>python.exe copy_file.py input_file.txt output_file.txt
>>> 55+(5/0)
Traceback (most recent call last):
File “<pyshell#12>”, line 1, in <module>
55+(5/0)
ZeroDivisionError: integer division or modulo by zero
>>> 5+ repeat*2
Traceback (most recent call last):
File “<pyshell#13>”, line 1, in <module>
5+ repeat*2
NameError: name ‘repeat’ is not defined
>>> ‘5’+5
Traceback (most recent call last):
File “<pyshell#14>”, line 1, in <module>
‘5’+5
TypeError : cannot concatenate ‘str’ and ‘int’ objects
The last line of the error message indicates what happened. Exceptions come
in different types, and the type is printed as part of the message: the types in the
example are ZeroDivisionError, NameError and TypeError. The string printed
as the exception type is the name of the built-in exception that occurred. This is true
for all built-in exceptions, but need not be true for user-defined exceptions (although
it is a useful convention). Standard exception names are built-in identifiers (not
reserved keywords).
The rest of the line provides detail based on the type of exception and what
caused it.
The preceding part of the error message shows the context where the exception
happened, in the form of a stack traceback. In general it contains a stack traceback
listing source lines; however, it will not display lines read from standard input.
Files , Modules and Packages 5.15
KeyError Raised when the specified key is not found in the dictionary.
Raised when an identifier is not found in the local or global
NameError
namespace.
Raised when trying to access a local variable in a function
UnboundLocalError
or method but novalue has been assigned to it.
5. 16 Problem Solving and Python Programming
Base class for all exceptions that occur outside the Python
EnvironmentError
environment.
Raised when an input/ output operation fails, such as the
IOError print statement orthe open() function when trying to open
a file that does not exist.
OSError Raised for operating system-related errors.
5. 4 Handling Exceptions
Python provides two very important features to handle any unexpected error
in your Python programs and to add debugging capabilities in them.
££ Exception Handling:
££ Assertions:
Files , Modules and Packages 5.17
Example
This example opens a file with write mode, writes content in the file and comes
out gracefully because there is no problem at all
try:
fp = open(“test_exception.txt”, “w”)
fp.write(“Exception handling”)
exceptIOError:
print “Error: File don\’t have read permission”
else:
print “Written successfully”
fp.close()
Example:
This example opens a file with read mode, and tries to write the file where
you do not have write permission, so it raises an exception
try:
fp = open(“test_exception.txt”, “r”)
fp.write(“Exception handling”)
exceptIOError:
print “Error: File don\’t have read permission”
else:
print “Written successfully”
fp.close()
This kind of a try-except statement catches all the exceptions that occur. Using
this kind of try-except statement is not considered a good programming practice
though, because it catches all exceptions but does not make the programmer identify
the root cause of the problem that may occur.
5.4.3The except Clause with Multiple Exceptions
You can also use the same except statement to handle multiple exceptions as
follows “
try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list, then execute this
block.
......................
else:
If there is no exception then execute this block.
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
You cannot use else clause as well along with a finally clause.
Example
This example opens a file with write mode, writes content in the file and comes
out gracefully because there is no problem at all
try:
fp = open(“test_exception.txt”, “w”)
fp.write(“Exception handling”)
exceptIOError:
print “Error: File don\’t have read permission”
else:
print “Written successfully”
finally:
print “Closing file”
fp.close()
try:
fp = open(“test_exception.txt”, “r”)
fp.write(“Exception handling”)
exceptIOError:
print “Error: File don\’t have read permission”
else:
print “Written successfully”
finally:
print “Closing file”
fp.close()
In the above two examples, one script didn‘t raise exception and another script
raise exception. But we can see that in both cases finally block gets executed.
5.4.5 Argument of an Exception
An exception can have an argument, which is a value that gives additional
information about the problem. The contents of the argument vary by exception.
You capture an exception’s argument by supplying a variable in the except clause
as follows “
try:
You do your operations here;
......................
exceptExceptionType, Argument:
You can print value of Argument here...
If you write the code to handle a single exception, you can have a variable
follow the name of the exception in the except statement. If you are trapping multiple
exceptions, you can have a variable follow the tuple of the exception.
This variable receives the value of the exception mostly containing the cause
of the exception. The variable can receive a single value or multiple values in the
5. 22 Problem Solving and Python Programming
form of a tuple. This tuple usually contains the error string, the error number, and
an error location.
Example
Following is an example for a single exception
deftemp_convert(var):
try:
returnint(var)
exceptValueError, Argument:
print “The argument is not a numbers\n”, Argument
temp_convert(“abc”)
Example
An exception can be a string, a class or an object. Most of the exceptions that
the Python core raises are classes, with an argument that is an instance of the
class. Defining new exceptions is quite easy and can be done as follows “
deffunctionName( level ):
if level < 1:
raise “Invalid level!”, level
# if we raise the exception,code below to this not executed
Note: In order to catch an exception, an “except” clause must refer to the same
exception thrown either class object or simple string. For example, to capture above
exception, we must write the except clause as follows
try:
Business Logic here...
except “Invalid level!”:
Exception handling here...
else:
Rest of the code here...
5. 5 Modules
A module allows you to logically organize your Python code. Grouping related
code into a module makes the code easier to understand and use. A module is a file
that contains a collection of related functions. Python has lot of built-in modules;
math module is one of them. math module provides most of the familiar mathematical
functions.
Before we can use the functions in a module, we have to import it with an
import statement:
>>> import math
This statement creates a module object named math. If you display the module
object, youget some information about it:
>>>math
<module ‘math’ (built-in)>
The module object contains the functions and variables defined in the module
.To access one of the functions, you have to specify the name of the module and the
name of the function, separated by a dot (also known as a period). This format is
called dot notation.
>>>math.log10(200)
2.3010299956639813
>>>math.sqrt(10)
3.1622776601683795
5. 26 Problem Solving and Python Programming
Math module have functions like log(), sqrt(), etc… In order to know what
are the functions available in particular module, we can use dir() function after
importing particular module. Similarly if we want to know detail description about
a particular module or function or variable means we can use help() function.
Example
>>> import math
>>>dir(math)
[‘ doc ‘, ‘ name ‘, ‘ package ‘, ‘acos’, ‘acosh’, ‘asin’, ‘asinh’, ‘atan’, ‘atan2’, ‘atanh’,
‘ceil’, ‘copysign’, ‘cos’, ‘cosh’, ‘degrees’, ‘e’, ‘erf’, ‘erfc’, ‘exp’, ‘expm1’, ‘fabs’, ‘factorial’,
‘floor’, ‘fmod’, ‘frexp’, ‘fsum’, ‘gamma’, ‘hypot’, ‘isinf’, ‘isnan’, ‘ldexp’, ‘lgamma’, ‘log’, ‘log10’,
‘log1p’, ‘modf’, ‘pi’, ‘pow’, ‘radians’, ‘sin’, ‘sinh’, ‘sqrt’, ‘tan’, ‘tanh’, ‘trunc’]
>>>help(pow)
Help on built-in function pow in module builtin :
pow(...)
pow(x, y[, z]) -> number
5.5.1Writing Modules
Any file that contains Python code can be imported as a module. For example,
suppose you have a file named addModule.py with the following code:
def add(a, b):
result = a + b
print(result)
add(10,20)
If you run this program, it will add 10 and 20 and print 30. We can import it
like this:
>>> import addModule
30
>>>addModule
<module ‘addModule’ from ‘G:/class/python/code\addModule.py’>
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 ‘; in that case, the test code
runs. Otherwise, if the module is being imported, the test code is skipped. Modify
add Module.py file as given below.
def add(a, b):
result = a + b print(result)
if name == ‘ main ‘:
add(10,20)
_name has module name as its value when it is imported. Warning: If you
import a module that has already been imported, Python does nothing. It does not
re-read the file, even if it has changed. If you want to reload a module, you can use
the built-in function reload, but it can be tricky, so the safest thing to do is restart
the interpreter and then import the module again.
5. 28 Problem Solving and Python Programming
5. 6 Packages
Packages are namespaces which contain multiple packages and modules
themselves. They are simply directories, but with a twist.
Each package in Python is a directory which must contain a special file called
init .py. This file can be empty, and it indicates that the directory it contains is a
Python package, so it can be imported the same way a module can be imported.
If we create a directory called sample_package, which marks the package
name, we can then create a module inside that package called sample_module. We
also must not forget to add the init .py file inside the sample_package directory.
To use the module sample_module, we can import it in two ways:
>>> import sample_package.sample_module
or:
>>>fromsample_package import sample_module
5. 7 Word Count
Example.
Following program print each word in the specified file occurs how many times
import sys
defword_count(file_name):
try:
file=open(file_name,”r”)
wordcount={}
entier_words=file.read().split()
for word in entier_words:
Files , Modules and Packages 5.29
count 2
word 2
file 1
many 1
is 1
in 1
times 1
how 1
program 1
which 1
each 1
the 1
appears 1
s
Above program shows the file handling with exception handling and command
line argument.While running, if you give command line like below, it will read the
text file with the name, that is specifies by command line argument one and calculate
the count of each word and print it.
c:\Python27>python wordcount1.py word_count_input.txt
While running, if you give command line like below(ie, no command line
argument), On behalf of exception handling it will ask for file name and then do the
same operation on the newly entered file.
c:\Python27>python wordcount1.py
Program also handle file not found exception, if wrong file name is entered. It
will ask for new file name to enter and proceed.
Example.
Following program counts number of words in the given file.
Files , Modules and Packages 5.31
import sys
defword_count(file_name):
count=0
try:
file=open(file_name,”r”)
entier_words=file.read().split()
for word in entier_words:
count=count+1
file.close();
print (“%s File have %d words” %(file_name,count))
exceptIOError:
print (“No file found with name %s” %file_name)
fname=raw_input(“Enter
New File Name:”) word_count(fname)
try:
word_count(sys.argv[1])
exceptIndexError:
print(“No file name passed as command line Argument”)
fname=raw_input(“Enter File Name:”)
word_count(fname)
Above program also shows the file handling with exception handling and
command line argument.While running, if you give command line like below, it will
read the text file with the name, that is specifies by command line argument one and
count number of word present in it and print it.
5. 32 Problem Solving and Python Programming
While running, if you give command line like below (ie, no command line
argument), On behalf of exception handling it will ask for file name and then do the
same word counting operation on the newly entered file.
c:\Python27>python wordcount2.py
Program also handle file not found exception, if wrong file name is entered. It
will ask for new file name to enter and proceed.
5. 8 Copy File
This is a Python Program to copy the contents of one file into another. In order
to perform the copying operation we need to follow the following steps.
1. Open source file in read mode.
2. Open destination file in write mode.
3. Read each line from the input file and write it into the output file.
4. Exit.
Also we include command line argument for passing source and destination
file names to program. Also exception handling is used to handle exception that
occurs when dealing with files.
import sys
def copy(src,dest):
try:
source=open(src,’r’)
destination=open(dest,’w’)
while(True):
new_line=source.readline()
ifnew_line==’’:
break
destination.write(new_line)
source.close()
destination.close()
Files , Modules and Packages 5.33
exceptIOError:
print (“Problem with Source or Destination File Name “)
source_name=raw_input(“Enter New Source File Name:”)
destination_name=raw_input(“Enter NewDestination File Name:”)
copy(source_name,destination_name)
try:
copy(sys.argv[1],sys.argv[2])
exceptIndexError:
print(“Insufficent Command line argument!”)
source_name=raw_input(“Enter Source File Name:”)
destination_name=raw_input(“Enter Destination File Name:”)
copy(source_name,destination_name)
finally:
print(“Copying Done......“)
Sample Programs
Exercise : 1 with Solution
Write a Python program to read an entire text file.
Sample Solution:-
Python Code:
Contain of text.txt
def file_read(fname):
txt = open(fname)
print(txt.read())
file_read(‘test.txt’)
5. 34 Problem Solving and Python Programming
Modules
Sample Output:
Welcome to w3resource.com.
Append this text.Append this text.Append this text.
Append this text.
Append this text.
Append this text.
Append this text.
def file_read(fname):
with open (fname, “r”) as myfile:
data=myfile.readlines()
print(data)
file_read(‘test.txt’)
To find the name of this module, we can use the __name__ attribute.
>>> calc.__name__
5. 40 Problem Solving and Python Programming
Output
‘calc’
We can now use functions from this module:
We can also assign one of these functions a name:
>>> fd=calc.floordiv
>>> fd(5.5,4)
Output
1.0
>>> fd(9,4)
Output
2
>>> type(fd(9,4))
Output
<class ‘int’>
>>> type(fd(5.5,4))
Output
<class ‘float’>
Output
2.25
>>> fd(9,4)
Output
2
We can also import all from a module:
>>> from calc import *
>>> floordiv(9,4)
Output
2
This will import all names other than those beginning with an underscore(_).
However, we disparage this use, as it makes for poorly readable code.
We can also import a module under an alias.
>>> import calc as cal
>>> cal.sub
Output
<function sub at 0x0655CC90>
How to Execute Python Modules as Scripts?
Look at the following code:
5. 42 Problem Solving and Python Programming
def add(a,b):
print(a+b)
def sub(a,b):
print(a-b)
def mul(a,b):
print(a*b)
def div(a,b):
print(a/b)
def exp(a,b):
print(a**b)
def floordiv(a,b):
print(a//b)
if __name__ == “__main__”:
import sys
if int(sys.argv[1])==1:
add(int(sys.argv[2]),int(sys.argv[3]))
elif int(sys.argv[1])==2:
sub(int(sys.argv[2]),int(sys.argv[3]))
These last few lines let us use the sys module to deal with command line
arguments. To execute subtraction, this is what we type in the command prompt:
C:\Users\lifei\Desktop\calc>python calc.py 2 3 4
-1
This way, you can complete the code for other operations as well. Hence, we’ve
created a script. But we can also import this normally like a module:
>>> import calc
>>>
Output
‘3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 32 bit
(Intel)]’
5. 44 Problem Solving and Python Programming
Output
[‘__displayhook__’, ‘__doc__’, ‘__excepthook__’, ‘__interactivehook__’, ‘__
loader__’, ‘__name__’, ‘__package__’, ‘__spec__’, ‘__stderr__’, ‘__stdin__’,
‘__stdout__’, ‘_clear_type_cache’, ‘_current_frames’, ‘_debugmallocstats’,
‘_enablelegacywindowsfsencoding’, ‘_getframe’, ‘_home’, ‘_mercurial’, ‘_
xoptions’, ‘api_version’, ‘argv’, ‘base_exec_prefix’, ‘base_prefix’, ‘builtin_
module_names’, ‘byteorder’, ‘call_tracing’, ‘callstats’, ‘copyright’, ‘displayhook’,
‘dllhandle’, ‘dont_write_bytecode’, ‘exc_info’, ‘excepthook’, ‘exec_prefix’,
‘executable’, ‘exit’, ‘flags’, ‘float_info’, ‘float_repr_style’, ‘get_asyncgen_
hooks’, ‘get_coroutine_wrapper’, ‘getallocatedblocks’, ‘getcheckinterval’,
‘getdefaultencoding’, ‘getfilesystemencodeerrors’, ‘getfilesystemencoding’,
‘getprofile’, ‘getrecursionlimit’, ‘getrefcount’, ‘getsizeof’, ‘getswitchinterval’,
‘gettrace’, ‘getwindowsversion’, ‘hash_info’, ‘hexversion’, ‘implementation’,
‘int_info’, ‘intern’, ‘is_finalizing’, ‘last_traceback’, ‘last_type’, ‘last_value’,
‘maxsize’, ‘maxunicode’, ‘meta_path’, ‘modules’, ‘path’, ‘path_hooks’,
‘path_importer_cache’, ‘platform’, ‘prefix’, ‘set_asyncgen_hooks’, ‘set_
coroutine_wrapper’, ‘setcheckinterval’, ‘setprofile’, ‘setrecursionlimit’,
‘setswitchinterval’, ‘settrace’, ‘stderr’, ‘stdin’, ‘stdout’, ‘thread_info’, ‘version’,
‘version_info’, ‘warnoptions’, ‘winver’]
>>> for i in dir(calc): print(i)
Output
__builtins__
__cached__
__doc__
__file__
__loader__
__name__
__package__
Files , Modules and Packages 5.45
__spec__
add
div
exp
floordiv
mul
sub
And without any arguments, dir() returns a lilst of the names that we have
defined currently.
>>> dir()
Output
Output
[‘ArithmeticError’, ‘AssertionError’, ‘AttributeError’, ‘BaseException’,
‘BlockingIOError’, ‘BrokenPipeError’, ‘BufferError’, ‘BytesWarning’,
‘ChildProcessError’, ‘ConnectionAbortedError’, ‘ConnectionError’,
‘ConnectionRefusedError’, ‘ConnectionResetError’, ‘DeprecationWarning’,
‘EOFError’, ‘Ellipsis’, ‘EnvironmentError’, ‘Exception’, ‘False’,
‘FileExistsError’, ‘FileNotFoundError’, ‘FloatingPointError’,
‘FutureWarning’, ‘GeneratorExit’, ‘IOError’, ‘ImportError’, ‘ImportWarning’,
‘IndentationError’, ‘IndexError’, ‘InterruptedError’, ‘IsADirectoryError’,
‘KeyError’, ‘KeyboardInterrupt’, ‘LookupError’, ‘MemoryError’,
‘ModuleNotFoundError’, ‘NameError’, ‘None’, ‘NotADirectoryError’,
‘NotImplemented’, ‘NotImplementedError’, ‘OSError’, ‘OverflowError’,
5. 46 Problem Solving and Python Programming
This was all on Python modules. Hope the Python Modules article was
informative.
Python Interview Questions on Modules
1. What is module in Python? Explain with example.
2. Explain the purpose for using Python modules.
3. How many modules are there in Python?
4. How to install and open a Python module?
5. Where are Python modules stored?
Conclusion
While this is all about Python modules, we suggest you should also read about
Packages in Python. Then, maybe you should switch to Packages vs Modules.
Packages
Python Packages Tutorial – How to Create Your Own Package
What are Python Packages?
In our computer systems, we store our files in organized hierarchies. We don’t
Files , Modules and Packages 5.47
store them all in one location. Likewise, when our programs grow, we divide it into
packages.
In real-life projects, programs are much larger than what we deal with in our
journey of learning Python. A package lets us hold similar modules in one place.
Like a directory may contain subdirectories and files, a package may contain
sub-packages and modules. We have been using modules a lot in the previous lessons.
Remember math, os, and collections? Those were all modules that ship with
Python officially. We will discuss the difference between a module and a package in
our next lesson.
But for now, let’s dive into the world of Python packages.
Structure of Python Packages
As we discussed, a package may hold other Python packages and modules. But
what distinguishes a package from a regular directory? Well, a Python package must
have an __init__.py file in the directory.
You may leave it empty, or you may store initialization code in it. But if your
directory does not have an __init__.py file, it isn’t a package; it is just a directory
with a bunch of Python scripts. Leaving __init__.py empty is indeed good practice.
Take a look at the following structure for a game:
5. 48 Problem Solving and Python Programming
Further Notes
When you import a package, only the modules directly under it are imported.
An import does not import the sub packages.
>>> import one
>>> one.two
Output
Traceback (most recent call last):File “<pyshell#488>”, line 1, in <module>one.
two.evenoddAttributeError: module ‘one’ has no attribute ‘two’
Also note that if you want to check where your Python packages are being
created, your path will look something like this:
C:\Users\lifei\AppData\Local\Programs\Python\Python36-32\Lib\site-
packages
How to Create Your Own Python Package?
Now, on to the most interesting part. Like we said, Python packages are
nothing but a dictionary with sub-packages and modules, and an __init__.py file.
In our example, this is the hierarchy we create:
Output
Enter a number7
Odd
>>> check()
Output
Enter a number0
Even
5. 9 With Answers
Two Marks Questions
1. What is module and package in Python?
In Python, module is the way to structure program. Each Python program file
is a module, which imports other modules like objects and attributes.
2. Explain how can you access a module written in Python from C?
We can access a module written in Python from C by following method,
Module ==PyImport_ImportModule(–<modulename>‖);
>>> f = open(“test.dat”,”w”)
>>> print f<open file _test.dat‘, mode _w‘ at fe820>
The open function takes two arguments. The first is the name of the file, and
the second is the mode. Mode “w” means that we are opening the file for writing.
5. Explain how the write method works on a file.
>>> f.write(“Now is the time”)
>>> f.write(“to close the file”)
Closing the file tells the system that we are done writing and makes the file
available for reading:
>>> f.close()
6. Which method is used to read the contents of a file which is already
created?
The read method reads data from the file. With no arguments, it reads the
entire contents of the file:
>>> text = f.read()
>>> print text
This example opens a file named words that resides in a directory named dict,
which resides in share, which resides in usr, which resides in the top-level
directory of the system, called .
10. Explain pickling and how import pickle works.
Pickling is so called because it –preserves– data structures. The pickle module
contains the necessary commands. To use it, import pickle and then open the
file in the usual way:
>>> import pickle
>>> f = open(“test.pck”,”w”)
The open function takes two arguments. The first is the name of the file, and the
second is the mode. Mode “w” means that we are opening the file for writing.
16. Explain how the write method works on a file.
>>> f.write(“Now is the time”)
>>> f.write(“to close the file”)
Closing the file tells the system that we are done writing and makes the file
available for reading:
>>> f.close()
17. Which method is used to read the contents of a file which is already
created?
The read method reads data from the file. With no arguments, it reads the
entire contents of the file:
>>> text = f.read()
>>> print text
This example opens a file named words that resides in a directory named dict,
which resides in share, which resides in usr, which resides in the top-level
directory of the system, called .
21. Explain pickling and how import pickle works.
Pickling is so called because it –preserves– data structures. The pickle module
contains the necessary commands. To use it, import pickle and then open the
file in the usual way:
>>> import pickle
>>> f = open(“test.pck”,”w”)
Files , Modules and Packages 5.55
5. Questions
Review 10
1. Answer the following questions.
a. Write a small code to illustrate try and except statements in Python.
(4 marks)
b. What are packages? Give an example of package creation in Python.
(4 marks)
c. Compare and contrast Extending and Embedding Python. (4 marks)
d. Write an algorithm to check whether a student is pass or fail, the total
marks of student being the input. (4 marks)
2. Answer the following questions.
a. Write a program to enter a number in Python and print its octal and
hexadecimal equivalent. (6 marks)
b. Demonstrate the use of Exception Handling in Python.(10 marks)
3. Answer the following questions.
a. What are modules in Python? Explain. (4 marks)
b. Explain in details about namespaces and scoping. (8 marks)
c. Explain about the import statement in modules. (4 marks)
4. Answer the following questions.
a. Explain about the different types of Exceptions in Python. ( 6 marks)
b. Describe about Handling Exceptions in detail with examples. (10 marks)
5. Explain in detail about Python Files, its types, functions and operations
that can be performed on files with examples. (16 marks)