Professional Documents
Culture Documents
UNIT-5 ppspNOTES
UNIT-5 ppspNOTES
UNIT-5 ppspNOTES
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
Example:
file = open('python.txt', 'r')
for i in file:
print (i)
Output
Welcome to python
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.
2.writelines()
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.
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)
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()
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']
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.
2.writelines()
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.
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)
Output
Python is the most easiest programming language.
the most easiest programming language..
7. flush()
Syntax: Filepointer . flush()
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()
Output
Python is
10
10. remove()
This method is used to remove a file or directory.
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.
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
Output
r+
13. name
Syntax: Filepointer . name
Output
myfile.txt
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
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.
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.
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
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.
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
Example:
Output:
Error: can't find file or read data
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.
6) try…..raise….except
This is used for forcefully raising the exception. Python allow as to forcefully raise an
exception if required.
Example:
Output:
ValueError: Error:we don't welcome, Robert
Output
Enter your name: Robert
The person should not be a Robert
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’
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”).
Example:
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
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()
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
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
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).
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.
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
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.
Output
keep smiling
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.
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