UNIT-5 ppspNOTES

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

Page |1

UNIT- V
FILES, MODULES, PACKAGES

Files and exception: 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
 File is a named location on disk to store related information.
 It is used to permanently store data in a memory.
File Types:
1. Text file
2. Binary file
1. Text file: It is a file that stores sequence of characters that can be sequentially
processed by a computer.
2. binary files: It store the data in the binary format (0’s and 1’s )

 When we want to read from or write to a file, we need to open it first. When we are
done, it needs to be closed so that the resources that are tied with the file are freed.
 Hence, in Python, a file operation takes place in the following order:
1. Open a file
2. Read or write (perform operation)
3. Close the file

How to open a file?


 Python has a built-in open() function to open a file. This function returns a file object
which consist file description, as it is used to read or modify the file accordingly.

Syntax: Fileobject = open( “file_name.txt”, ”mode” )

 We can specify the mode of the while opening it.


 In mode, we specify whether we want to read (r), write (w) or append (a) to the file. We
can also specify if we want to open the file in text mode or binary mode.

Example:
file = open('python.txt', 'r')
for i in file:
print (i)

Output
Welcome to python

GE3151 : PROBLEM SOLVING AND PYTHON PROGRAMMING


Page |2

Various file accessing modes

Difference between write and append mode

Reading and Writing files


Writing to a file
 There are two ways to write in a file.
 write() : Inserts the string str1 in a single line in the text file.
 writelines() : For a list of string elements, each string is inserted in the text file. Used to
insert multiple strings at a single time.
1. write()

Syntax:

 It writes the contents of string to the file. It has no return value. Due to buffering,
the string may not actually show up in the file until close() method is called.
Example:
f = open(“myfile.txt”, 'w')
str1="all is god"
f.write(str1)

GE3151 : PROBLEM SOLVING AND PYTHON PROGRAMMING


Page |3

f.close()
This code will create a new file named myfile.txt and write the content of str1 to it.

2.writelines()

Syntax: Filepointer . writelines(sequence)

 It writes a sequence of strings to the file usually a list of strings or any other iterable
data type. It has no return value.
 Used to insert multiple strings at a single time.
Example:
s1="We Welcome\n"
s2="All our dear students\n"
s3="To our college"
list1=*s1,s2,s3+
f = open("newfile.txt", 'w+')
f.writelines(list1)
f.close()
This code will create a new text file named newfile and write the content of List1 to it.

Reading from a file


There are three ways to read data from a text file.
1. read() : Returns the read bytes in form of a string. Reads n bytes, if no n specified,
reads the entire file.
2. readline() : Reads a line of the file and returns in form of a string. For specified n,
reads at most n bytes. However, does not reads more than one line, even if n exceeds
the length of the line.
3. readlines() : Reads all the lines and return them as each line a string element in a list.

1. read()
Syntax: filepointer.read(size)

 It reads the entire file and returns it contents in the form of a string.
 It reads the specified size of characters and return it if the size is mentioned.
 It reads at most size bytes from the file (less if the read hits EOF before obtaining size
bytes).
 If the size argument is negative or omitted, read all data until EOF is reached.
Example1:
f = open("newfile.txt", 'r')
x = f.read()
f.close()
print(x)

GE3151 : PROBLEM SOLVING AND PYTHON PROGRAMMING


Page |4

Output
We Welcome
All our dear students
To our college

Example2:
f = open(“newfile.txt", 'r')
x = f.read(6)
f.close()
print(x)

Output
We Wel

Example3:
f = open(“newfile.txt", 'r')
x = f.read(80)
f.close()
print(x)

Output
We Welcome
All our dear students
To our college

2. readline()
Syntax: Filepointer. readline(size)

 It reads the first line of the file i.e till a newline character or an EOF in case of a file
having a single line and returns a string.
 If the size argument is present and non-negative, it is a maximum byte count.
Assume myfile.txt contains “all is god” string inside it.
Example1:
f = open("myfile.txt", 'r')
y=f.readline()
f.close()
print(y)

Output
all is god

Example2:
f = open("myfile.txt", 'r')
y=f.readline(6)
f.close()

GE3151 : PROBLEM SOLVING AND PYTHON PROGRAMMING


Page |5

print(y)

Output
all is

3. readlines()
Syntax: Filepointer. readlines(sizehint)

 It reads the entire file line by line and updates each line to a list which is returned.
 If the optional sizehint argument is present, instead of reading up to EOF, whole lines
totaling approximately sizehint bytes.
Example1:
f = open(“newfile.txt", 'r')
y=f.readlines()
f.close()
print(y)

Output
*'We Welcome\n', 'All our dear students\n', 'To our college'+

Example2:
f = open(“newfile.txt", 'r')
y=f.readlines(10)
f.close()
print(y)

Output
['We Welcome\n']

Example3:
f = open(“newfile.txt", 'r')
y=f.readlines(15)
f.close()
print(y)

Output
['We Welcome\n', 'All our dear students\n']

Example4:
f = open(“newfile.txt", 'r')
y=f.readlines(35)
f.close()
print(y)
Output
['We Welcome\n', 'All our dear students\n', 'To our college']

GE3151 : PROBLEM SOLVING AND PYTHON PROGRAMMING


Page |6

File methods and objects

S.No. Methods Description

1 write() Writes the specified string to the file

2 writelines() Writes a list of strings to the file

3 read() Returns the file content

4 readline() Returns one line from the file

5 readlines() Returns a list of lines from the file

6 seek() Change the file position

7 flush() Flushes the internal buffer

8 close() Used to close the file

9 tell() Returns the current file position

10 remove() Used to remove a file or directory

11 rename() Used to rename the file or directory

12 mode This will return the name of the file.

13 name This will return the mode of the file

1. write()

Syntax:

 It writes the contents of string to the file. It has no return value. Due to buffering,
the string may not actually show up in the file until close() method is called.
Example:
f = open(“myfile.txt”, 'w')
str1="all is god"
f.write(str1)
f.close()
This code will create a new file named myfile.txt and write the content of str1 to it.

GE3151 : PROBLEM SOLVING AND PYTHON PROGRAMMING


Page |7

2.writelines()

Syntax: Filepointer . writelines(sequence)

 It writes a sequence of strings to the file usually a list of strings or any other iterable
data type. It has no return value.
 Used to insert multiple strings at a single time.
Example:
s1="We Welcome\n"
s2="All our dear students\n"
s3="To our college"
list1=*s1,s2,s3+
f = open("newfile.txt", 'w+')
f.writelines(list1)
f.close()

This code will create a new text file named newfile and write the content of List1 to
it.

3. read()
Syntax: filepointer.read(size)

 It reads the entire file and returns it contents in the form of a string.
 It reads the specified size of characters and return it if the size is mentioned.
 It reads at most size bytes from the file (less if the read hits EOF before obtaining size
bytes).
 If the size argument is negative or omitted, read all data until EOF is reached.
Example1:
f = open("newfile.txt", 'r')
x = f.read()
f.close()
print(x)

Output
We Welcome
All our dear students
To our college

4. readline()
Syntax: Filepointer. readline(size)

 It reads the first line of the file i.e till a newline character or an EOF in case of a file
having a single line and returns a string.
 If the size argument is present and non-negative, it is a maximum byte count.

GE3151 : PROBLEM SOLVING AND PYTHON PROGRAMMING


Page |8

Assume myfile.txt contains “all is god” string inside it.


Example1:
f = open("myfile.txt", 'r')
y=f.readline()
f.close()
print(y)

Output
all is god

5. readlines()
Syntax: Filepointer. readlines(sizehint)

 It reads the entire file line by line and updates each line to a list which is returned.
 If the optional sizehint argument is present, instead of reading up to EOF, whole lines
totaling approximately sizehint bytes.
Example1:
f = open(“newfile.txt", 'r')
y=f.readlines()
f.close()
print(y)

Output
*'We Welcome\n', 'All our dear students\n', 'To our college'+

6. seek()
Syntax: Filepointer . seek(offset, from_where)

It is used to change the file object’s position.


offset - indicates the number of bytes to be moved.
from_where - indicates from where the bytes are to be moved.
0- from the beginning
1- from the current position
2- from the last
Example1:
f = open("myfile.txt", 'r+')
print(f.read())
f.seek(10,0)
x=f.read()
print(x)
f.close()

Output
Python is the most easiest programming language.
the most easiest programming language..

GE3151 : PROBLEM SOLVING AND PYTHON PROGRAMMING


Page |9

7. flush()
Syntax: Filepointer . flush()

 This method flush the internal buffer.


 It has no return value.
 close() automatically flushes the data but if you want to flush the data before closing
the file then you can use this method.
Example:
f = open("myfile.txt", 'r+')
print(f.read())
f.flush()
f.close()

8. close()
 This method is used to close an opened file.
Syntax: Filepointer . close()

Example:
f =open("myfile.txt","r")
x=f.read()
f.close()
print(x)

Output
All is god

9. tell()
Syntax: Filepointer . tell()

 It returns an integer that tells us the current file pointer position.


Example:
f = open("myfile.txt", 'r+')
x=f.read(10)
print(x)
fpp=f.tell()
print(fpp)
f.close()

Output
Python is
10

10. remove()
 This method is used to remove a file or directory.

GE3151 : PROBLEM SOLVING AND PYTHON PROGRAMMING


P a g e | 10

 We need to import os module before using this method.


Syntax: os.remove (filename)

filename – name of the file to be removed from the memory


Example:
import os
os.remove(“file5.txt")
f = open("file5.txt", 'r+')
print(f.name)

Output
FileNotFoundError: [Errno 2] No such file or directory: 'file5.txt'

11. rename()
 This method is used to renames the file or directory.
 We need to import os module before using this method.

Syntax: os.rename(src, dst)

src: Source is the name of the file or directory. It should must already exist.
dst: Destination is the new name of the file or directory you want to change.
Example:
import os
os.rename("myfile.txt","file5.txt")
f = open("file5.txt", 'r+')
print(f.name)

Output
file5.txt

12. mode
Syntax: Filepointer . mode

 This will return the mode of the file.


Example:
f = open("myfile.txt", 'r+')
print(f.mode)
f.close()

Output
r+

GE3151 : PROBLEM SOLVING AND PYTHON PROGRAMMING


P a g e | 11

13. name
Syntax: Filepointer . name

 This will return the name of the file.


Example:
f = open("myfile.txt", 'r+')
print(f.name)
f.close()

Output
myfile.txt

GE3151 : PROBLEM SOLVING AND PYTHON PROGRAMMING


P a g e | 12

Errors and Exceptions


Errors
 Errors are the mistakes in the program also referred as bugs. They are almost always
the fault of the programmer. The process of finding and eliminating errors is called
debugging.
 Errors can be classified into three major groups:
1. Syntax errors
2. Runtime errors
3. Logical errors
1.Syntax errors
 Syntax errors are the errors which are displayed when the programmer do mistakes
when writing a program. When a program has syntax errors it will not get executed.
 Common Python syntax errors include:
1. leaving out a keyword
2. putting a keyword in the wrong place
3. leaving out a symbol, such as a colon, comma or brackets
4. misspelling a keyword
5. incorrect indentation
6. empty block

2.Runtime 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.
 When a program has runtime error I will get executed but it will not produce output.
 Common Python runtime errors include:
1. division by zero
2. performing an operation on incompatible types
3. using an identifier which has not been defined
4. accessing a list element, dictionary value or object attribute which doesn’t exist
5. trying to access a file which doesn’t exist

3. Logical errors:
 Logical errors are the most difficult to fix.
 They occur when the program runs without crashing, but produces an incorrect
result.
 Common Python logical errors include:
1. Using the wrong variable name
2. Indenting a block to the wrong level
3. Using integer division instead of floating-point division
4. Getting operator precedence wrong

GE3151 : PROBLEM SOLVING AND PYTHON PROGRAMMING


P a g e | 13

5. making a mistake in a boolean expression

Exceptions:
 An exception(runtime time error)is an error, which occurs during the execution of a
program that disrupts the normal flow of the program's instructions.
 When a Python script raises an exception, it must either handle the exception
immediately otherwise it terminates or quit.

Types of inbuilt exceptions that may thrown by python are:


1. IOError
Raised when an input/ output operation fails, such as the print statement or the open()
function when trying to open a file that does not exist.
2. SyntaxError
Raised when there is an error in Python syntax.
3. IndentationError
Raised when indentation is not specified properly.
4. TypeError
Raised when an operation or function is attempted that is invalid for the specified data
type.
5. ValueError
Raised when the built-in function for a data type has the valid type of arguments, but
the arguments have invalid values specified.
6. RuntimeError
Raised when a generated error does not fall into any category.
7. NameError
Raised when an identifier is not found in the local or global namespace.
8. KeyError
Raised when the specified key is not found in the dictionary.
9. IndexError
Raised when an index is not found in a sequence.
10.ImportError
Raised when an import statement fails.
11.ZeroDivisionError
Raised when division or modulo by zero takes place for all numeric types.

GE3151 : PROBLEM SOLVING AND PYTHON PROGRAMMING


P a g e | 14

Exception handling in python


 If you have some suspicious code that may raise an exception, you can defend your
program by placing the suspicious code in a try: block.
 After the try: block, include an except: statement, followed by a block of code which
handles the problem as elegantly as possible.
 When a Python script raises an exception, it must either handle the exception
immediately otherwise it terminates and quits.

Exception Handling is done by try and except blocks.


 Suspicious code (code with possibility of having errors) that may raise an exception will
be placed in try block.
 A block oh code which handles the exception ( error) is placed in except block.

Syntax: try:
Suspicious code that may raise an exception may be
placed here.
except :
A block of code which handles the exception
else:
If there is no exception then execute this block.

Different ways of catching exceptions:


1. try….except
2. try….except ….else
3. try….except ….else…finally
4. try….except inbuilt exception
5. try….except…except inbuilt exception
6. try…..raise….except

1)Try….except
Syntax:
try:
Suspicious code that may raise an exception may be placed here.
except :
A block of code which handles the exception

Example:

Output
Enter your age: p

GE3151 : PROBLEM SOLVING AND PYTHON PROGRAMMING


P a g e | 15

Enter valid age

2)Try….except…else
If there is no exception in try block then else block statements get executed.
Syntax: try:
Suspicious code that may raise an exception may be placed here.
except :
A block of code which handles the exception
else:
If there is no exception then execute this block.

Example:

Output
Error: can't find file or read data

Example-2:

Output
Content written in to the file successfully

3)Try….except…else….finally
 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.

GE3151 : PROBLEM SOLVING AND PYTHON PROGRAMMING


P a g e | 16

Syntax:

try:
Suspicious code that may raise an exception may be placed here.
except :
A block of code which handles the exception.
else:
If there is no exception then execute this block.
finally:
A block of code that should always be executed, whether the try-block
raised an exception or not.

Example:

Output
Error: can't find file or read data
Ready to execute other statements

4) try….except inbuilt exception


 This is used to catch inbuilt exceptions
Syntax:
try:
Suspicious code that may raise an exception
may be placed here.
except inbuilt exception name:
A block of code which handles the exception

Example:

GE3151 : PROBLEM SOLVING AND PYTHON PROGRAMMING


P a g e | 17

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

5) try….except… except inbuilt exception


This is used to catch more than one inbuilt exceptions. But one at a time.
Syntax: try:
Suspicious code that may raise an exception
may be placed here.
except < inbuilt exception-1 name >:
A block of code which handles the exception-1
except < inbuilt exception-2 name >:
A block of code which handles the exception-2

Example-1:

Output
Unable to write in to the file , check the mode

Here we have opened the file in read mode and trying to write in to the file. This is a
kind of IOError. So it is handle by IOError exception handler. Hence the above output
came.

Example-2:

Output
The input to file should be of string type

We know that the input to a file is always string. But here we are passing an integer
value as a input to the string. This is a kind of TypeError.
So it is handle by TypeError exception handler. Hence the above output came.

GE3151 : PROBLEM SOLVING AND PYTHON PROGRAMMING


P a g e | 18

6) try…..raise….except
This is used for forcefully raising the exception. Python allow as to forcefully raise an
exception if required.

Forcefully raising the exception

Example:

Output:
ValueError: Error:we don't welcome, Robert

In this program we are forcefully raising an exception for a specified condition.


Here if the input given is “Robert” the exception occurs and the given error message will
be thrown as ValueError .

Forcefully raising the exception and handling it

Python allow as to forcefully raise an exception and handle it.


Example:

Output
Enter your name: Robert
The person should not be a Robert

In this program we are forcefully raising an exception for a specified condition.


Here if the input given is “Robert” the exception occurs and the given error message will
be thrown as ValueError . This exception will be handled by except block.

GE3151 : PROBLEM SOLVING AND PYTHON PROGRAMMING


P a g e | 19

Format operator
 The argument of write( ) has to be a string, so if we want to put other values along with
the string in a file, we have to convert them to strings.
1. Convert number into string using str() function.
>>> x = 52
>>> f.write(str(x))

Output
‘52’

2. Convert to strings using format operator, %


General form:
print (“format string”%(tuple of values))
file.write(“format string”%(tuple of values)
Example:
>>>age=13
>>>print(“The age is %d”%age)
The age is 13

 The first operand is the format string, which specifies how the second operand is
formatted.
 The result is a string. For example, the format sequence '%d' means that the second
operand should be formatted as an integer (d stands for “decimal”).

Sl.No Format character Description


1 %c Character
2 %s String
3 %d Decimal integer
4 %f Floating point number
5 %X Hexadecimal

Example:

GE3151 : PROBLEM SOLVING AND PYTHON PROGRAMMING


P a g e | 20

Output

 If there is more than one format sequences in the string the second argument has to be
tuple.
Examples:

Output

 The number of elements in the tuple has to match the number of format sequences in
the string. Also, the type of the elements have to match the format sequences.
Example:

Output

GE3151 : PROBLEM SOLVING AND PYTHON PROGRAMMING


P a g e | 21

Command line arguments


 The command line argument is used to pass input from the command line to your
program when they are started to execute.
 Handling command line arguments with Python need sys module.
 sys module provides information about constants, functions and methods of the python
interpreter.
 sys.argv* + is used to access the command line argument. The argument list starts from
0.
Here:
sys.argv*0+= gives file name
sys.argv*1+=provides access to the first input

Example:
Program name: command_line.py

Here,
python - invoke python interpreter
Then we have to pass the arguments required
The first argument (argv*0+) is always the program name. The next argument is argv*1+
and so on.
Here 5 and 2 are other input arguments argv*1+ and argv*2+….

Example-2
Python program to copy the content of one file to another using the concept of
command line arguments.
import sys
sf=open(sys.argv*1+,"r")
x=sf.read()
df=open(sys.argv*2+,"w+")
df.write(x)
df.seek(0)
print(df.read())
sf.close()
df.close()

GE3151 : PROBLEM SOLVING AND PYTHON PROGRAMMING


P a g e | 22

Save the program as name file_copy.py in the desktop. Create the source file (myfile.txt)
and write some content in to it. Also create an empty destination file (newfile.txt) in the
same directory where the python code is saved.

Output

GE3151 : PROBLEM SOLVING AND PYTHON PROGRAMMING


P a g e | 23

Modules
 A module is a file containing Python definitions ,functions, statements and instructions.
 Standard library of Python is extended as modules.
 To use modules in a program, programmer needs to import the module.
Eg: import math
 To get information about the functions and variables supported module you can use the
built-in function help(Module name)
Eg: help(“math”).
 The dir() function is used to list the variables and functions defined inside a module. If
an argument, i.e. a module name is passed to the dir, it returns that modules variables
and function names else it returns the details of the current module.
Eg: dir(math)

Example:
Python program to find the square root and factorial of a number using predefined
functions

Steps for Creating user defined modules and reusing it.


Step-1
Create the module by including the required functions ,variables, classes , statements
etc.
Example:

GE3151 : PROBLEM SOLVING AND PYTHON PROGRAMMING


P a g e | 24

Step-2
Save this module name as mymodule.py (user defined name)

Step-3
Use the functions, variables and statements in mymodule.py in your new program.
Example:

Output
25
120
30

OS module in python
 Python OS module provides the facility to establish the interaction between the user
and the operating system.
 It offers many useful OS functions that are used to perform OS-based tasks and get
related information about operating system.
 For this we need to import the os module to interact with the underlying operating
system. So, import it using the import os statement before using its functions.
 There are some functions in the OS module which are given below.
1. os.name()
2. os.mkdir()
3. os.getcwd()
4. os.chdir()
5. os.rename()
6. os.rmdir

1. os.name()
 This function provides the name of the operating system module that it imports.
Example:
import os
print(os.name)

Output
Windows nt

2. os.mkdir()
 This function is used to create new directory (folder).

GE3151 : PROBLEM SOLVING AND PYTHON PROGRAMMING


P a g e | 25

Example:
import os
os.mkdir("d:\\newdir")

It will create the new directory named newdir in the path specified in the string
argument of the function.

3. os.getcwd()
 This method returns the current working directory(CWD) of the file.
Example:
import os
print(os.getcwd())

Output
C:\Users\raj\AppData\Local\Programs\Python\Python310

4. os.chdir()
 This method is used to change the current working directory.
Example:
import os
os.chdir(“d:\\newdir”)
print(os.getcwd())

Output
d:\newdir

5. os.rename()
 A file or directory can be renamed by using this function.
 A user can rename the file if it has privilege to change the file.
Example:
import os
fd = "python.txt"
os.rename(fd,‘mypython.txt')
 Now the existing file named python.txt is renamed as mypython.tx

6 os.remove()
 This method in the OS module removes the specified directory either with an absolute
or relative path.
 However, you can not remove the current working directory. To remove it, you must
change the current working directory, as shown below.
Example:
import os
os.rmdir("D:\\newdir")
 Now the directory named newdir inside the drive D was removed.

GE3151 : PROBLEM SOLVING AND PYTHON PROGRAMMING


P a g e | 26

Illustrative program-1
word count
Word count and line count:-
 Python program to count the number of words and lines in a file.
 The existing file myfile.txt

Program:

Output
The number of words: 6
The number of lines: 2

GE3151 : PROBLEM SOLVING AND PYTHON PROGRAMMING


P a g e | 27

Illustrative program-2
Copyfile
Description: Create two empty files and write some content in to the first file, then copy
this content of this first file to the second file and display the content of second file.

Python program to copy the content of one file to another file.


Program:
sf=open( "myfile.txt","w+” )
sf.write( "keep smiling“ )
sf.seek(0)
x=sf.read()
sf.close()
df=open( "newfile.txt","w+” )
df.write(x)
df.seek(0)
y=df.read()
print(y)
df.close()

Output
keep smiling

GE3151 : PROBLEM SOLVING AND PYTHON PROGRAMMING


P a g e | 28

Illustrative program-3
Voter’s age validation
Description:
Write a python program to check whether a person is eligible for voting by validating the
age.

Program:
age = int(input("Enter Age : "))
if age>=18:
status="Eligible"
else:
status="Not Eligible"
print("You are ",status," for Vote.")

Output
Enter Age : 25
You are Eligible for Vote.

GE3151 : PROBLEM SOLVING AND PYTHON PROGRAMMING


P a g e | 29

Illustrative program-4
Marks range validation (0-100)
Python program to implement student mark range validation using the concept of
exception handling.
try:
m1=int(input("Enter mark 1:"))
m2=int(input("Enter mark 2:"))
m3=int(input("Enter mark 3:"))
m4=int(input("Enter mark 4:"))
m5=int(input("Enter mark 5:"))
if(m1<0 or m1>100)or (m2<0 or m2>100)or(m3<0 or m3>100)or(m4<0 or
m4>100)or(m5<0 or m5>100):
raise valueError("Enter the postive number which is less than 100")

except valueError:
print("Enter the integer no")
except Exception:
print("Exception occurs")
else:
total=m1+m2+m3+m4+m5
avg=total/5
if(avg>=90):
print("Grade: A")
elif(avg>=80 and avg<90):
print("Grade: B")
elif(avg>=70 and avg<80):
print("Grade: C")
elif(avg>=60 and avg<70):
print("Grade: D")
else:
print("Grade: F")

Output
Enter mark 1:88
Enter mark 2:78
Enter mark 3:98
Enter mark 4:99
Enter mark 5:97
Grade: A

GE3151 : PROBLEM SOLVING AND PYTHON PROGRAMMING

You might also like