0% found this document useful (0 votes)
2 views21 pages

Problem Solving Python Programming Unit - V

unit v is about files in python

Uploaded by

sivashankari.m
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views21 pages

Problem Solving Python Programming Unit - V

unit v is about files in python

Uploaded by

sivashankari.m
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT V FILES, MODULES, PACKAGES

Files and exceptions: text files, reading and writing files, format operator; command line arguments, errors
and exceptions, handling exceptions, modules, packages; Illustrative programs: word count, copy file, Voter’s age
validation, Marks range validation (0-100).

FILES AND EXECPTION


Definition:
Files is a named location on disk to store related information, settings, or commands in secondary storage
device like magnetic disks, magnetic tapes and optical disks.
Types of Files:
There are two types of files:
Text files
Binary files
Text files:
Text files are sequence of lines or sequence of character in text format. Each line is terminated with a special
character, called EOL or end of line character.
Binary files:
Binary files is any type of files other than a text files.
File Operation:
1. Open()
2. read()
3. write()
4. close()

Opening a file:
This function creates a file object, which would be utilized to call other support methods associates with it.

Syntax : file_object= open(‘filename’ , ’mode’)


Here,
Filename: The file name argument is a string value that contains the name of the file that you want to access.
Mode: The access mode determines the mode in which the files have to be opened, (i.e)., read, write, append
etc.

Modes Description
Open a file for reading only. The file pointer is placed at the beginning of the
r
file. This is default mode.
Open a file for reading only in binary format. The file pointer is placed at the
rb
beginning of the file. This is default mode.
Open a file for both read and write. The file pointer is placed at the beginning of
r+
the file.
Open a file for both read and write in binary format. The file pointer is placed at
rb+
the beginning of the file
Open a file for writing only. Overwrite the file if exists. If the files does not
w
exists, creates a new file for writing.

1
Open a file for writing only in binary format. Overwrite the file if exists. If the
wb
files does not exists, creates a new file for writing.
Open a file for both read and write. Overwrite the file if exists. If the files does
w+
not exists, creates a new file for writing and reading.
Open a file for both read and write in binary format. Overwrite the file if exists.
wb+
If the files does not exists, creates a new file for writing and reading.
a Open a file for appending. This file pointer is placed at the end of the file.
Open a file for appending only in binary format. This file pointer is placed at the
ab end of the file, if exists. That is, the file is in the appending mode. If the files
does not exists, creates a new file for writing.
Open a file for appending and reading. This file pointer is placed at the end of
a+
the file, if exists.
Open a file for appending and reading in binary format. This file pointer is placed
ab+
at the end of the file, if exists. It creates a new file for reading and writing.

Example: fn=open(‘D:/[Link]’,’r’)

Writing into a file:


write() is used to write a string to an already opened files. To write into a file, it is needed to open a file in write
‘w’, append ‘a’ or exclusive ‘x’ mode.

Syntax : [Link](“filename”,”mode”)

Example:
f=open(‘D:/[Link]’,’w’)
[Link](“welcome\n”)
[Link](“thank you”)
[Link]()

New file is created in the name “[Link]” and content is written


Welcome
Thank you
Use of with statement:
 Because every call on function open should have a corresponding call on method close, python
provides a with statement that automatically closes a file when the end of the block is reached.

Syntax:
with open (filename, mode) as variable :
block
Example:
with open (“[Link]”, “r”) as file:
contents=[Link]( )
Print(contents)

Methods of writing a file:


1. Write() – writes a single line into the specified file.
2. Writelines()- writes multiple line into specified file.

2
Writelines():
The writelines method put multiple data into the file.
The writelines() method writes any string to an open file.
Syntax: [Link](string)

[Link]:
Output:
f=open(‘D:/[Link]’,’w’)
This is my book
str=‘this is my book\n I found it here’ I found it here

[Link](str)
[Link]()

Reading a file:
This method helps to just view the content of given input files. To read the content of a file, one must open the
file in reading mode.
Syntax: filevariable=open(‘filename’,’r’)
Methods used in reading a file.
1. read(size)
2. Readline()
3. Readlines()
[Link](size)
This read() specifies the size of data to be read from input files.
If size not mentioned, it reads the entire files and cursor waits in last position of files.
Ex.
f=open(“[Link]”, ”r”)
print(“The first 5 characters of the file are:\n”, [Link](5))
[Link]()

The content of the file100 is:

OUTPUT:

3
Readline():
This method is used to read a single line from the input file, till the new line character occur.
It doesn’t takes any argument.

Syntax: [Link]()
ex.
f=open(“[Link]”,”r”)
print(“reading content of the file by realine() method:\n”)
print([Link]())
[Link]()

Readlines():
This method is used to read and display all the line from the input file.

Syntax: [Link]()
ex.
f=open(“[Link]”,”r”)
print(“reading content of the file by realines() method:\n”)
print([Link]())
[Link]()

File object attributes:


name: Return the name of the file. It is a read-only attribute and may not be present on all file-like objects. If
the file object was created using the open() function, the file’s name is returned. Otherwise, some string indicates the
source of the file object is returned.

encoding: It returns the encoding this file uses, such as UTF-8. This attribute is read-only. When Unicode
strings are written to a file, they will be converted to byte strings using this encoding. It may also be None. In that
case, the file uses the system default encoding for converting Unicode strings.

mode: Returns the file access mode used while opening a file.

closed: Returns True if a file is closed. It is a Boolean value indicating the current state of the file object.

newline: Files opened in universal newline read mode keep track of the newlines encountered while reading
the file. The values are ‘\r’, ‘\n’, ‘\r\n’, None (no newlines read yet), or a tuple containing all the newline types seen.
For files not opened in universal newline read mode, the value of this attribute will be None.
Closing a file:
The close() methods of a file object flushes any unwritten information and closes the file object, after which
no more writing can be done.

Syntax: [Link]()
[Link]: Output:
Open(‘[Link]’,’wb’) Name of the file: [Link]

Print(“name of the file:”,[Link])


[Link]()

4
Example: Python program to implement all file read operation:
fn=open(‘D:/[Link]’,’r’)
print([Link]())
[Link](0)
Output:
print([Link](4)) Welcome to the world of robotics
print([Link]()) Welc
4
[Link](0) Welcome to the world of robotics
Welcome to the world of robotics
print([Link]()) and automation
[Link](0)
print([Link]())

[Link]:
Welcome to the world of robotics
and automation

FILE METHODS

Methods Description
[Link]() Close the file. A closed file cannot be read or write anymore.
Flush the internal buffer, like stdio’s fflush. This may be a no-op on
[Link]()
some file like objects.
Return the integer file description that is used by underlying
[Link]()
implementation to request I/O operation from os.
[Link]() Return True if the file is connected to a tty(-like) devices, else False.
Read at most size bytes from files (less if the read hits EOF before
[Link]([size])
obtaining size bytes)
Read one entries line from the file. A trailing newline character is kept
[Link]([size])
in the string.
Read until EOF using readline() and return a list containing the lines.
[Link]([sizehint]) If the optional sizehint of argument is present, instead of reading up to
EOF, whole line totaling approximately sizehint bytes are read.
[Link](offset[,whence]) Set the files current position.
[Link]() Return the files current position
Truncates the files size. If the optional size argument is present, the file
[Link]([size])
is truncated to that size.
[Link](str) Writes a string to the files. There is no return value.
Writes a sequence of string to a file. The sequences can be any
[Link](sequence)
iterable. Object producing string, typically a list of strings.
[Link]() Return true if file stream can be read from.
[Link]() Return true if file stream supports random access.
[Link](0 Return true if file stream can be written to.

5
Tell() and seek():
Tell() method display the current position of cursor from the input files.
Seek() takes an argument and moves the cursor to the specified position which is mentioned as argument.
Syntax: print([Link]())
print([Link]())
Example:
fn=open(‘D:/[Link]’,’r’)
print([Link]())
[Link](0)
print([Link](4)) Output:
print([Link]()) Welcome to the world of robotics
[Link](0) Welc
print([Link]()) 4
[Link](0) Welcome to the world of robotics
print([Link]()) Welcome to the world of robotics
and automation
[Link]:
Welcome to the world of robotics
and automation

FORMAT OPERATOR
String formatting is the process of infusing things in the strings dynamically and presenting the strings.
There are four different ways to perform string formatting.
1. Formatting with % operator
2. Formatting with format() string methods.
3. Formatting with string literals, called f-strings.
4. String template class

1. Formatting with % operator:


It’s the oldest method of string formatting. Here we use the modulo % operator. The modulo % is also known
as the “string formatting operator”.
‘%s’ is used to inject strings.
‘%d’ is used to integer
‘%f’ for floating point values.
‘%b’ for binary format.
Example:
Print(‘joe stood up and %s to the crowd.’%’spoke’)
Print(‘there are %d dogs.’%4)
Print(‘floating point numbers:%.2f’ %(13.144))
Output:
Joe stood up and spoke to the crowd
There are 4 dogs
Floating point numbers:13.14

2. Formatting with format() string method:


Format() method was introduced with Python3 for handling complex string formatting more efficiently.
Formatters work by putting in one or more replacement fields and placeholders defined by a pair of curly braces {}
into a string and calling the [Link]().

Syntax: ‘String here {} then also {}’.format(‘something1′,’something2’)

6
Example:
print('We all are {}.'.format('equal'))
Output: We all are equal.
The format() method has many advantages over the placeholder method:
 We can insert object by using index-based position:
Example: print('{2} {1} {0}'.format('directions','the', 'Read'))
Output: Read the directions.

 We can insert objects by using assigned keywords:


Example: print('a: {a}, b: {b}, c: {c}'.format(a = 1, b = 'Two',c = 12.3))
Output: a: 1, b: Two, c: 12.3
 We can reuse the inserted objects to avoid duplication:
Example: print ('The first {p} was alright, but the {p} {p} was tough.'.format(p = 'second'))
Output: The first second was alright, but the second second was tough.

Float precision with the format() method:

Syntax: {[index]:[width][.precision][type]}

The type can be used with format codes:


 ‘d’ for integers
 ‘f’ for floating-point numbers
 ‘b’ for binary numbers
 ‘o’ for octal numbers
 ‘x’ for octal hexadecimal numbers
 ‘s’ for string
 ‘e’ for floating-point in an exponent format
Example:
print('The value of pi is: %1.5f' %3.141592) # vs.
print('The value of pi is: {0:1.5f}'.format(3.141592))

Output:
The value of pi is: 3.14159
The value of pi is: 3.14159

7
COMMAND LINE ARGUMENT
The arguments that are given after the name of the program in the command line shell of the operating
system are known as Command Line Arguments. Python provides various ways of dealing with these types of
arguments. The three most common are:
1. Using [Link]
2. Using argparse module

[Link] [Link]:
The sys module provides functions and variables used to manipulate different parts of the Python runtime
environment. This module provides access to some variables used or maintained by the interpreter and to functions
that interact strongly with the interpreter.
One such variable is [Link] which is a simple list structure. It’s main purpose are:
 It is a list of command line arguments.
 len ([Link]) provides the number of command line arguments.
 [Link][0] is the name of the current Python script.

Example: Let’s suppose there is a Python script for adding two numbers and the numbers are passed as command-
line arguments.

# Python program to demonstrate command line arguments


import sys

# total arguments
n = len ([Link])
print ("Total arguments passed:", n)

# Arguments passed
print("\nName of Python script:", [Link][0])
print("\nArguments passed:", end = " ")
for i in range(1, n):
print([Link][i], end = " ")

# Addition of numbers using argparse module


Sum = 0
for i in range(1, n):
Sum += int([Link][i])
print("\n\nResult:", Sum)

Output:

8
2. Using argparse module:
Using argparse module is a better option than the above two options as it provides a lot of options such as
positional arguments, default value for arguments, help message, specifying data type of argument etc.
Example:
import argparse
# Initialize parser
parser = [Link]()
parser.parse_args()
Output:

ERRORS AND EXCEPTION


Exception:
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.
When a Python code comes across a condition it can't handle, it raises an exception. An object in Python that
describes an error is called an exception.

They are mainly two types of errors:


1. Syntax errors :
The python finds the syntax errors when it parses the source program. Once it finds 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 symbols such as comma, colon, brackets, quotes
(v) Empty blocks
2. Runtime errors:
If a program is syntactically correct-that is, free of syntax errors it will be executed by the python
interpreter. However, the program may exit unexpectedly during execution if it encounters a runtime error.

9
The run time errors are not detected while parsing the source program, but will occur due to some logical
mistake.
Eg of runtime error are:
1) Trying to access a file which does not exist.
2) Using an identifier which is not defined.
3) Performing operations of incompatible type elements
4) Division by Zero
Such errors are handled using exception handling.

[Link]. Name of the Exception Description of the Exception

1 Exception All exceptions of Python have a base class.

2 StopIteration If the next() method returns null for an iterator, this exception is raised.

3 SystemExit The [Link]() procedure raises this value.

Excluding the StopIteration and SystemExit, this is the base class for all
4 StandardError
Python built-in exceptions.

5 ArithmeticError All mathematical computation errors belong to this base class.

This exception is raised when a computation surpasses the numeric data type's
6 OverflowError
maximum limit.

7 FloatingPointError If a floating-point operation fails, this exception is raised.

For all numeric data types, its value is raised whenever a number is attempted
8 ZeroDivisionError
to be divided by zero.

9 AssertionError If the Assert statement fails, this exception is raised.

10 AttributeError This exception is raised if a variable reference or assigning a value fails.

When the endpoint of the file is approached, and the interpreter didn't get any
11 EOFError
input value by raw_input() or input() functions, this exception is raised.

12 ImportError This exception is raised if using the import keyword to import a module fails.

If the user interrupts the execution of a program, generally by hitting Ctrl+C,


13 KeyboardInterrupt
this exception is raised.

14 LookupError LookupErrorBase is the base class for all search errors.

15 IndexError This exception is raised when the index attempted to be accessed is not found.

When the given key is not found in the dictionary to be found in, this exception
16 KeyError
is raised.

This exception is raised when a variable isn't located in either local or global
17 NameError
namespace.

10
This exception is raised when we try to access a local variable inside a
18 UnboundLocalError
function, and the variable has not been assigned any value.

19 EnvironmentError All exceptions that arise beyond the Python environment have this base class.

If an input or output action fails, like when using the print command or the
20 IOError
open() function to access a file that does not exist, this exception is raised.

22 SyntaxError This exception is raised whenever a syntax error occurs in our program.

23 IndentationError This exception was raised when we made an improper indentation.

This exception is raised when the [Link]() method is used to terminate the
24 SystemExit Python interpreter. The parser exits if the situation is not addressed within the
code.

This exception is raised whenever a data type-incompatible action or function


25 TypeError
is tried to be executed.

This exception is raised if the parameters for a built-in method for a particular
26 ValueError
data type are of the correct type but have been given the wrong values.

This exception is raised when an error that occurred during the program's
27 RuntimeError
execution cannot be classified.

If an abstract function that the user must define in an inherited class is not
28 NotImplementedError
defined, this exception is raised.

Handling an exception
When it raises an exception, it must either handle the exception immediately else it terminates and
quits. The exception handling mechanism uses the try….except…..else blocks.
try: includes suspicious code.
After the try: block, include an except: statement, followed by a block of code which handles the problem as
elegantly as possible.
Syntax
Here is simple syntax of try....except...else blocks −
try:
write the suspicious code here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
Note:
1. A single try statement can have multiple except statements. This is useful when the try block contains
statements that may throw different types of exceptions.
2. You can also provide a general except clause, which handles any exception.
3. After the except clause(s), you can include an else-clause. The code in the else-block executes if the code in
the try: block does not raise an exception.
4. The else-block is a good place for code that does not need the try: block's protection.

11
Example 1:
try:
fh = open("testfile", "w")
[Link]("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
[Link]()
Output:
Written content in the file successfully

Example 2:
try:
fh = open("testfile", "r")
[Link]("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
Output:
Error: can't find file or read data

The except Clause with No specific Exceptions:


You can also use the except statement with no exceptions defined as follows –
Syntax:
try:
You do your operations here;
......................
except:
If there is any exception, then execute this block.
......................
else:
If there is no exception then execute this block.

Example:
try:
n=int(input(“Enter some number”))
except
print(“you have entered wrong data”)
else:
print(“You have entered:”,n)
Output:
Enter some number a
You have entered a wrong data
Enter some number 10
You have entered :10
Note: This kind of a try-except statement catches all the exceptions that occur.

12
The except Clause with Multiple Exceptions:
You can also use the same except statement to handle multiple exceptions as follows −
Syntax:
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.
Example:
try:
a=int(input(“Enter the value of a”))
b=int(input(“Enter the value of b”))
c=a/b
except value error:
print (“You have entered wrong data”)
except Zerodivision error:
print (“Divide by zero error!!!”)
else:
print (“The result”,c)
Output:
Enter the value of a:10
Enter the value of b:a
You have entered wrong data

The try-finally Clause:


You can use a finally: block along with a try: block. The finally block is a place to put any code that must
execute, whether the try-block raised an exception or not.
The syntax of the try-finally statement is this −

Syntax:
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................

Example:
try:
fh = open("testfile", "w")
[Link]("This is my test file for exception handling!!")
finally:
print "Error: can\'t find file or read data"

Output:
Error: can't find file or read data

13
Raising an Exceptions:
You can raise exceptions in several ways by using the raise statement. The general syntax for the raise statement is as
follows.
Syntax
raise [Exception [, args [, traceback]]]
Here, Exception is the type of exception (for example, NameError) and argument is a value for the exception
argument. The argument is optional; if not supplied, the exception argument is None.
The final argument, traceback, is also optional (and rarely used in practice), and if present, is the traceback
object used for the exception.
Example:

def functionName( level ):


if level < 1:
raise "Invalid level!", level
# The code below to this would not be executed
# if we raise the exception

User-Defined Exceptions:
Python also allows you to create your own exceptions by deriving classes from the standard built-in exceptions.
Here is an example related to RuntimeError. Here, a class is created that is subclassed from RuntimeError.
This is useful when you need to display more specific information when an exception is caught.
In the try block, the user-defined exception is raised and caught in the except block. The variable e is used to
create an instance of the class Networkerror.

class Networkerror(RuntimeError):
def __init__(self, arg):
[Link] = arg
So once you defined above class, you can raise the exception as follows −

try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print [Link]

14
MODULES
A Python module is a file containing Python definitions and statements. A module can define functions,
classes, and variables. A module can also include runnable code. Grouping related code into a module makes the
code easier to understand and use.

Example:
def add(x, y):
return (x+y)
def subtract(x, y):
return (x-y)

Import Module in Python


We can import the functions, and classes defined in a module to another module using the import
statement in some other Python source file.
Syntax
import module

Example:
# importing module [Link]
import calc
print([Link](10, 2))

Output: 12

The from-import Statement in Python


Python’s from statement lets you import specific attributes from a module without importing the module as
a whole.
Example:
from math import sqrt, factorial
print(sqrt(16))
print(factorial(6))

Output:
4.0
720
Import all Names :
The * symbol used with the from import statement is used to import all the names from a module to a current
namespace.
Syntax:
from module_name import *

Example:
from math import *
print(sqrt(16))
print(factorial(6))
Output: 4.0
720

Renaming the Python module:


We can rename the module while importing it using the keyword.
Syntax: Import Module_name as Alias_name
Example: # importing sqrt() and factorial from the

15
# module math
import math as mt
print([Link](16))
print([Link](6))

Python built-in modules


There are several built-in modules in Python, which you can import whenever you like.

Example:
import math
print([Link](25))
print([Link])
print([Link](2))
print([Link](60))
print([Link](2))
print([Link](0.5))
print([Link](0.23))
print([Link](4))

import random
print([Link](0, 5)) # printing random integer between 0 and 5
print([Link]()) # print random floating point number between 0 and 1
print([Link]() * 100) # random number between 0 and 100
List = [1, 4, True, 800, "python", 27, "hello"]
print([Link](List))

import datetime
from datetime import date
import time
# Returns the number of seconds since the
# Unix Epoch, January 1st 1970
print([Link]())
# Converts a number of seconds to a date object
print([Link](454554))

16
Packages
A package is a collection of modules. 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.

Importing module from a package:


We can import modules from packages using the dot (.) operator.
For example, if want to import the start module in the above example, it is done as follows. import [Link].
Now if this module contains a function named select_difficulty(), we must use the full name to reference it.
[Link].select_difficulty(2)
If this construct seems lengthy, we can import the module without the package prefix as follows.
from [Link] import start
We can now call the function simply as follows.
start.select_difficulty(2)
Yet another way of importing just the required function (or class or variable) form a module within a package
would be as follows.
From [Link]
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 [Link], similar as for module
search path.

17
ILLUSTRATIVE PROGRAM
1. Word Count [Link] files:
import sys def copyFile(oldFile, newFile):
file=open("/Python27/[Link]","r+") f1 = open(oldFile, "r")
wordcount={} f2 = open(newFile, "w")
for word in [Link]().split(): while True:
if word not in wordcount: text = [Link](50)
wordcount[word] = 1 if text == "":
else: break
wordcount[word] += 1 [Link](text)
[Link](); [Link]()
print ("%-30s %s " %('Words in the File' , 'Count')) [Link]()
for key in [Link](): return
print ("%-30s %d " %(key , wordcount[key]))

2 Mark Questions and Answers

[Link] is a text file?


A text file is a file that contains printable characters and whitespace, organized in to lines separated by
newline characters.

[Link] a python program that writes “Hello world” into a file.


f =open("[Link]",'w')
[Link]("hello world")
[Link]()

[Link] a python program that counts the number of words in a file.


f=open("[Link]","r")
content =[Link](20)
words =[Link]()
print(words)

[Link] are the two arguments taken by the open() function?


The open function takes two arguments : name of the file and the mode of operation.
Example:
f = open("[Link]","w")

[Link] is a file object?


A file object allows us to use, access and manipulate all the user accessible files. It maintains the state
about the file it has opened.
Example:
f = open("[Link]","w") // f is the file object.

[Link] information is displayed if we print a file object in the given program?


f= open("[Link]","w")
print f
The name of the file, mode and the location of the object will be displayed.

[Link] is an exception?
Whenever a runtime error occurs, it creates an exception. The program stops execution and prints an error
message.
Example:
#Dividing by zero creates an exception: print 55/0
ZeroDivisionError: integer division or modulo

18
[Link] are the two parts in an error message?
The error message has two parts: the type of error before the colon, and specification about the error after
the colon.
Example:
>>> 10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ZeroDivisionError: integer division or modulo by zero

[Link] are the error messages that are displayed for the following exceptions?
1. Accessing a non-existent list item
2. Accessing a key that isn’t in the dictionary
3. Trying to open a non-existent file
4. IndexError: list index out of range
5. KeyError: what
6. IOError: [Errno 2] No such file or directory: 'filename'

[Link] do you handle the exception inside a program when you try to open a non-existent file?
filename = raw_input('Enter a file name: ') try:
f = open (filename, "r") except IOError:
print 'There is no file named', filename

11. How does try and execute work?


The try statement executes the statements in the first block. If no exception occurs, then except statement is
ignored. If an exception of type IOError occurs, it executes the statements in the except branch and then continues.
Example:
try:
print "Hello World" except:
print "This is an error message!"

[Link] is the function of raise statement? What are its two arguments?
The raise statement is used to raise an exception when the program detects an error. It takes two
arguments: the exception type and specific information about the error.

[Link] is a pickle?
Pickling saves an object to a file for later retrieval. The pickle module helps to translate almost any type of
object to a string suitable for storage in a database and then translate the strings back in to objects.

[Link] is the use of the format operator?


The format operator % takes a format string and a tuple of expressions and yields a string that includes the
expressions, formatted according to the format string.
Example:
>>> nBananas = 27
>>> "We have %d bananas." % nBananas 'We have 27 bananas.'

[Link] are the two methods used in pickling?


The two methods used in pickling are,
1. [Link]()
2. [Link]().

To store a data structure, dump method is used and to load the data structures that are dumped, load
method is used.

[Link] are modules?(or) Write a note on modular design (Jan-2018)


• Modules are files containing Python definitions and statements (ex: [Link])
• Modules can contain executable statements along with function definitions.
• Each modules has its own private symbol table used as the global symbol table all functions in the
module.
• Modules can import other modules.

19
[Link] is a package?
Packages are namespaces that contain multiple packages and modules themselves. They are simply
directories.
Example:
from [Link]
import select_difficulty

[Link] a Python script to display the current date and time. (Jan-2018)
import datetime
print(“date and time”, [Link]())

[Link] is the special file that each package in Python must contain?
Each package in Python must contain a special file called init .py. init .py can be an empty file but it
is often used to perform setup needed for the package(import things, load things into path, etc).
Example :
package/
init .py [Link] [Link] [Link] subpackage/
init .py [Link] [Link]

[Link] do you use command line arguments to give input to the program? (or) What is command line
argument? (May 2019) (Nov / Dec 2019)
Python sys module provides access to any command-line arguments via [Link]. [Link] is the list of
command-line arguments. len([Link]) is the number of command-line arguments.
Example:
import sys
program_name = [Link][0]
arguments = [Link][1:]
count = len(arguments)

[Link] are the different file operations?


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

[Link] are the different file modes?


 'r' - Open a file for reading. (default)
 'w - Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
 'x' - Open a file for exclusive creation. If the file already exists, the operation fails.
 'a' - Open for appending at the end of the file without truncating it. Creates a new file if it does not
exist.
 't' - Open in text mode. (default)
 'b' - Open in binary mode.
 '+' - Open a file for updating (reading and writing)

[Link] to view all the built-in exception in python.


The built-in exceptions using the local() built-in functions as follows.
Syntax: >>> locals()[' builtins ']
This will return us a dictionary of built-in exceptions, functions and attributes.

[Link] do you mean IndexError?


IndexError is raised when index of a sequence is out of range.
Example:
>>> l=[1,2,3,4,5]
>>> print l[6]
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module> print l[6]
IndexError: list index out of range

20
[Link] the syntax error in the code given:
while True print(‘Hello World’) (Jan 2019)
In the above given program, colon is missing after the condition. The right way to write the above program is,
while True:
print(‘Hello World’)

[Link] the different types errors arises during programming. Interpret the following python code
>>>import os (May 2019)
>>>cwd = [Link]()
>>>print cwd

Basic types of errors:


1. Syntax Error: Raised by the parser when a syntax error is encountered. Semantic Error:
2. Semantic Error: Raised by the parser when there is logical error in the program.
Here in the above given program, Syntax error occurs in the third line (print cwd) SyntaxError: Missing
parentheses in call to 'print'.

[Link] method to rename and delete files (Nov/Dec 2019)


[Link](current_file_name, new_file_name)
[Link](file_name)

21

You might also like