Python Unit 2
Python Unit 2
JNTU+fYDERA
PART-B
ESSAY QUESTIONS WITH SOLUTIONS
2.1
2.1.1 File Object.
Q . Give a detail description about file objects.
Answer t
File Objects in Python
File objects in python are used to read and/or write data to a file. They indicate a connection to a file on the disk.
file is a built-in type, the need to import module is not required.
Writing to a File
A file must bé created first before writing to it. This is done by creating a file object and notifying python n
to be s(Titten.The following statement creates a simple file. n
file(path,
Here, the first argument represents the path where the file is created. The argument "w" tells the python
created for writing purpose. If it is not mentioned the python assumes the file is created for reading
Data into the file is written using the following statement.
>>>my_file.write("PythonProgramming\n");
The line breaks in python are added by the programmer itself using the escape sequence "\n". The text can be
by using the write method again. If the string data exceeds one line then it can be continued in the next lines too.
Example
>>>my_file.write(
Python is a programming language
. It is easy and user-friendly
... It has many methods and
. Functions in it.
Line breaks can be added in between a multi-line string. The data can be printed using the print statementas follows
"End of the file".
The output prints >>> as the prompt while >> adds the output to the file to suppress the line break, terminate
statement by comma. After writing the text, the file must be closed by deleting the file object. This can be done
by thefollow.
statement.
del my_file.
ading From a File
In order to read a file, a file object must be opened first then "r" argument must be specified. Which
tells python
le has been opened for the reading purpose.
The following statement opens a file for reading.
>>>input = file(path, "r")
Here, path specifies the location to the file that is to be read. An exception is raised if the
file is not found.
line" reads the date one line at a time.
>>>input.readline( )
"Python Programming\n"
Look for the SIA GROUP LOGO on the TITLE COVER beforeyoubuy
Ibe newline character returned at the end of the method
which not been read
Strtng read method can also read the entire file a' once. I blS
content yet, Consider the following statement.
input.rcad( )
text
outputs the foljowmg,
ISa programming language. It is easy and user-friendly.
Jt has many methods and functions in it••
The newline characters are printed as line breaks since print
qtatement has been used. The file must be closed after reading.
following statement deletes the file.
del input
l. open( )
2. file(
open( )
nis function is used to open a file for reading or writing. Its syntax is shown below:
file_object opcn(file_name, accesg_mode = 'w', buffering = -l)
Parameters
file name: A string value that specifies the name ofthe file to open. It may be relative or absolute pathname.
access_ mode : It specifies the mode in which the file has to be opened. Python defines several access modes. For example.
•w' for writing, 'r' for reading, 'a' for append and so on. This is an optional parameter and if it is not used, the default
access mode i.e., "r" will be used. The table below shows various access modes for file objects.
Mode Action
Opens the file for read operation.
rU Opens the file for read operation with support for universal NEWLINE.
w Opens file for performing write operation. If file already exist, it is truncated before performing write.
a Opens file for performing append operation. Data is written from the EOF.
Opens the file for performing both read and write operation.
Opens file for performing both read and write. Note that during write operation it behaves like 'w' mode.
Opens file for performing both read and write. Note that during write operation it behaves like 'a' mode.
rb Opens file for performing binary read.
wb Opens file for performing binary write.
ab Opens file for performing binary append.
It is similar to r+ mode, but treats the file as binary file.
It is similar to w+ mode, but treats the file as binary file.
It is similar to a+ mode, but treats the file as binary file.
Table: Access Modes for File open( ) Function
Look for the SIA GROUP LOGO on the TITLE COVER beforeyoubuy
and Modules 2.7
Measure offset isatty( )
$ beøce from the ThJSmethod. used to determine whether the
Beginmng of filc file is a tty.like deuce. Jf yes. 't returns 'True',
otherwise 'faJse%
Current location
Syntax : file.isatty( )
End of the file (v) truncate( )
This method. 'truncates' (delete the contents)
location of file of the file to the specified size. If the size is ru»t
returns the current
It returns the distance in specified, then the file will be truncatsd OJIcurrent
method' the file. file. Jn other words, file position.
beginning ofthe
Syntax : file.truncate(sizæ)
) ret%rently located on 12e byte from
QIY-•Explain in brief the file system of python and
file.
ing of the file built-in methods.
) Answer Model Paper-I", 04(•)
• file.tell(
Methods File System
us to iterate through lines file system of python consists ofseveral OS modules
Methods,allow help of a 'for-loop' to perform tasks related to files and directory. The OS also
done with the
serves as a front end module to a pure OS-dependent module.
release of python 2.2, iteration was It avoids direct usage direct usage of OS dependent modules
the by loading the required module for the operating system being
follows:
as installed.
.readline( )
in filel The methods supported by the OS modules can be put
each line into three categories. They are as follows,
to method readline( ) was 1. File processing methods
2.2, the call
iteration as follows,
— %nce, we can perform 2. Directory methods
3. Permissions methods.
in file)
1. File Processing Methods
line
File processing methods like rename( ) and remove( ) are
file.next( ) can also be used, to read
no more lines in the by the OS modules in order to perform file processing
in the file. If there are
exception is raised.
'stoplteration• these methods are as follows,
Methods
rename( ) method
This method enables a user to rename a file. The general
dose() syntax of this method is,
close a file after
is used, to explicitly
lbs method mechanism, rename(current_file_name,new_file_name)
Pythongarbage collection
closes the file, if the file object Here, current file name is the current name of file and
yweverimplicitly
to zero. new_fiJe_name is the new name to be given for the file.
r%ence is decreased
Example
Syox .• file.close( )
>>import OS
>>> OS.rename('somefile', 'newfile')
descriptor (integer
Tbsmethod.retums the file When the above code is executed the rename( ) method
useful for
value)for the file. The descriptor is
various lower-level operations. renames 'somefile' to 'newfile'.
perfrrmtng
remove( ) method
. file.fileoo()
lhis method enables a user to delete a file from the
operating system. This can be done by providing file name that
Thismethod,will immediately write the contents is to be deleted as an argument. ne syntax of remove( ) method
ofouvutbufferto the desired file. is as follows,
remove (file_name)
: file.flush( )
Look for the SIA GROUP LOGO on the TITLE COVER beforeyoubuy
Line Arguments
to the line arguments.
than script name upon Invocation are called command
argument is from command line. And argc is a variable that holds count of arguments. first argc
f! cotsin which every
game 0
the send output
based systems, the commands act as programs that accept input and perform some operation and then directed
first
ofdata. This is the data that is sent as input to next program. Instead of saving the output on disk space, it is
as input. This can be implemented through command line input or standard input.
All these t&9ksare
Thecommand line arguments allow the programme to being the program with different characteristics.
getopt and optparse.
thebackgroUnd.Python maintains two modules for processing command line arguments, they are
done File System, File Execution
ritein brief about file system. Explain briefly about file execution.
wer:
system
file refer Unit-Il, Q13, Topic: File System.
Foranswer system
interface to operating from
Filesystemis allowed to be accessed through Python OS module. It acts as a primary can be anyone
The os module is a front-end to real module that is loaded. This module
and services from Python.
facilities
etc.
Mac,nt, Dos, posix, gets loaded.
os2 Thesemodules need not be imported directly. When os module is imported the required module automatically
operations such as
and process execution environment, the os module the major file system
themanagingthe processes functions of os
remaining files, traversing directory tree and managing file accessibility. The file/directory access
files,
deleting
as follows,
noduleare
Processing
file
Functions Description
*stat( ) It returns file statistics
remove( )/unlink( ) It deletes the file
symlink( ) It creates a symbolic link
walk( ) It generates filename in a directory tree
utime( ) It updates time stamp
mkfifo( )/mk nod( ) It creates named pipe/create file system node
rename( )/renames( ) It renames the file
tmpfile( ) It creates and opens new temporary file
Directories/FoIders
Functions Description
chroot( ) It changes root directory of the current process
chdir( )/fchdir( ) It changes the working directory/via a file descriptor
listdir( ) It lists all the files in directory
mkdir( )/makedir( ) It creates directory(is)
remdir( )/removedirs( ) It removes directory(is)
getcud/getcwdu( ) It returns current working directory
Aecess/Permissions
Functions Description
access( ) It verifies permission modes
unmask( ) It sets the default permission modes
chmod( ) It changes permission modes
chown( )/Jchown( ) It changes owner and group ID
Functions Description
It used to o file
read( Vwrite( ) It rcads!writcs data to tile descrtptor
du )'du 2( ) It du licntes the tile desert tor
Device Numbers
Functions Description
from raw
major( Vrninor( ) It extracts major/minor device number
device number.
makedev( ) It generates raw device number from major and
minor device numbers.
File System Execution
TOrun an operating system command, initially invoke a binary executable or some other type of scnpt. This
execution of another file somewhere else on the system. Running execution of other python code might call some
interpreter. But this might not be the case every time.
The most common execution scenarios are as follows.
Executing another Python script.
Creating and managing the subprocess.
Executing a command that needs input.
Invoking a command across the network.
Executing a set of dynamically generated Python statements.
Executing external command or program.
Importing Python module.
Executing a command that creates output and needs processing.
Execution of another Python programs involves the below steps.
1. Import the Module
Initially import the module, this will cause the code at top level of that module to execute.
2. Execute the Modules as Scripts
Execute the module as script from shell or DOS prompt.
2.1.5 Persistent Storage Modules,Related Modules
Q17. Discuss in brief about persistent storage modules.
Answer
The system operations needs user to input the data. In case of iterations the same data might be entered multiple
&
repeatedly. The persistent storage archives the data so that it can be accessed in future rather than re entering the
Mostly the storage modules deal with storing the strings of data. Other than this even Python objects can be archivd
persistent storage modules are as follows,
Module Description
Pickle and Marshal They allow to pickle the python objects. It converts the primitive types to binary set ofbytesu
can be stored or transmittedover network. Pickling is also called as serializing,flattering
marshalling. Marshal can handle the simple python objects and pickle can transformrectrsi•e
objects that are multi referenced from different places and user defined classes and imstance
DBM style modules They writes data in pure DBM format. There are various implementations such as dbtn.goa
dumbdbm and dbhashnsddb, They provide names space for the objects.
Schelve Module This module makes use of any dbm module for finding the appropriateDBMmodule.It
use cpickle module to perform the pickling process. It only allows concurrentreadacces•
database file.
and Modules 2.11
modules.
various related
't out
Input/output ore as followg.
related to files and
Functions Description
It allows access to comma rated value files
It allows access to BZ2 com sed files
It is encoding/decodin of hrnary strings to/from text strings
se6Ü
It is encoding/decoding of binary and ASCII enccded b'nary 'trin
binøsCi1
It compares directones and files.
tilecrn
It reads and writes the TAR archive files
tar61e
It iterates over lines of multi le input text files
fileinput
It provides command line argument arstng/rnampulatton
getoptjoptparse
It provides unix-style wildcard character matching
lob/fnmatch
It reads and writes GNU zip files
gzip/zlib
It offers high level file access functionality.
shutil
It implements file like interface on string objects.
c!string 10
It generates temporary files or file names.
tempfile
It provides tools and utihties to read and write ZIP archive files.
zipfile
It provides uuencode and uudecode files.
uu
2.2 EXCEPTIONS
2.2.1 Exceptions in Python
the exception handling in Python.
Explainabout ModelPaper-I,04(b)
ger :
as an action, that is taken
Exceptionis a run-time error, that halts the execution ofthe program. It is also described process. First
It is a two-phase
normalflow ofcontrol by python interpreter or programmer, because ofa runtime error.
ofcurrent
immediately stops the flow
it initiatessomething called 'raising an exceptions'. Though the interpreter known as, 'triggering',
it intimates that something is wrong and that needs to be rectified raising an exception is also
• 'or 'generating'.
by the python interpreter or
Insecondphase, actual exceptional handling takes place. Exceptions can be handled either course-of-action to be
er. Once an exceptional handling is initiated, programmer dictates an interpreter about the ignoring
some corrective measures, logging the error,
inorderto contain the errors. This course-of-action could be taking
according to the nature and severity
(or)aborting the program itself. The actions to subside the errors are customized,
oftheerror.
exceptions. try _ except statement,
'try_except' statementis used by Python, to handle exceptions. It also allow one to detect
mechanism to handle exceptions.
cnsistsOfcodeused to monitor for exceptions._lt also provides a
Syntax
try :
try_suite # Exceptions are detected here
exceptException[reason]:
except_suite # code to handle exceptions.
Usingthe above syntax, we can enter a code into our program to both detect and handle the error. In the 'try_suite'
bbckthecodethatmay raise the exception is placed. The type of exception that should be handled is specified, through 'except
statement.In 'except_suite' block we define code, telling the interpreter about the actions it must take after
Exception(reasonJ
exceptionis raised.
else :
z
finally :
Syntax Action
exclass
raise exclass Create an instance of
and raise an exception.
syøtas
Example
from myModule import classA. funcl, classB.
classlmp, func_Set
Alternatively,we can use the Python's standard
Esømple grouping mechanism i.e., parentheses to write multi-line import
moduleA, moduleB
importmyModule, statements as shown below.
WhenPython interpreter encounters the import from myModule import(classA, func 1, clasB, classlmp,
the module being imported.
it loads and executes
statement, func_set)
rules, however are applicable. That is, if module
scoping it gets local scope. And if it is However the most simple and obvious option is to use
isimportedfroma function, separate import statements as follows:
top-level then, it gets global scope.
„portedfrom
from myModule import classA, funcl
Thereis no hard-and-fast rule for writing import
However,the best practice is to import one module from myModule import classB, classlmp
statements,
the following order is maintained.
inonelineand that from myModule import func_set
(iii) Import Statement with •as'
Impon python standard library modules The word 'as', is an extension to import statement. It
gives another name (or alias), to the modules or elements that
are imported. In other words, we can bind a local name for the
imported items. This is very useful, when the original name of
the element being imported is either long or meaningless and
Importthird party modules we want to give it a short and more meaningful name. It is used
as follows:
import ModuleX7382.M0de1776-02 as Mode1776
Importapplication_specific modules
Original name(very long) Alias or local name
(short)
Alternatively,we can get another name without using
Remailingprogam the "as" keyword.
It is shown below.
import ModuleX7382-Mode1776-02
>>> Mode1776= ModelX7382-Mode1776-02
Figure:Ordering of Module Import Statements >>> del ModuleX7382-Mode1776-02
PECTRUN
RU-IN-ONEJOURNGL FOR ENCINEERINC STUDENTS SIA GROUP
2.22
Now, we can use the name 'Mode1776' instead of using
the long name
'ModuleX7382-M0de1776-02',
The "as" keyword can also be used, with "from-import"
statement. The following example shows the same.
fromExaustV-l import prog273279905LXI as
ProgLX1
Q32. Draw and explain the namespace relationship
between an application and an imported mod-
ule.
Answer ;
When a module is imported for the first time it creates
the namespace same as calling a ftnction creates a namespace.
A module is imported using the import statement. When
this statement is executed it assigns the module namespace to
the module name.
The module namespace contains the names bounded in
the module.
To access the names present in module namespace,
we
use the syntax. Module_name.Name.
For example, to access the variable 'q' defined in
module
module] we write,
>>>import module I
>>> module I .x
Example
Considera module that defines two
functions and an
application that imports this module tb call
a function.
#module I .py
print "Module! is executing"
defsimilarcase(x):,
return x.islower( ) or x.isupper(
)