0% found this document useful (0 votes)
31 views64 pages

Unit 5

Uploaded by

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

Unit 5

Uploaded by

selvaprabhu.t
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 64

UNIT 5

FILES, MODULES AND PACKAGES

1. Files : text files, reading and writing files, format


operator;
2. Command line arguments,
3. Errors and exceptions, handling exceptions,
4. Modules, Packages;
5. Illustrative programs: word count, copy file
FILES
File is a named location on disk to store related
information. It is used to permanently store data in a
memory (e.g. hard disk).

•As the part of programming requirement, we have to


store our data permanently for future purpose. For this
requirement we should go for files.

•Files are very common permanent storage areas to store


our data.
Types of Files:
Text Files: Usually we can use text files to store
character data Eg: abc.txt

Binary Files: Usually we can use binary files to store


binary data like images, video files, audio files etc...
Text Binary
File File

Text file is a sequence of A binary files store the data in


characters that can be the binary format (i.e. 0’s and
sequentially processed by a 1’s )
computer in forward direction.

Each line is terminated with a It contains any type of data


special character, called the EOL ( PDF , images , Word
or End of Line character doc,Spreadsheet, Zip files,etc)
Opening a File:
Before performing any operation (like read or write)
on the file, first we have to open the file. For this we
should use Python's inbuilt function open()

The allowed modes in Python are


f = open(filename, mode)
But at the time of open, we have to specify
mode, which represents the purpose of
opening file.
SYNTAX:

The allowed modes in Python are


f = open(filename, mode)

EXAMPLE:

f = open("abc.txt","w")

We are opening abc.txt file for writing data


Modes in file:

Mode Name
r read only mode
w write only
a appending mode
r+ read and write mode
w+ write and read mode
Differentiate write and append mode:

Write Mode Append Mode

It is use to write a string It is used to append (add) a


into a file. string into a file.
If file does not exist it If file does not exist it
creates a new file creates a new file.
If file is exist in the It will add the string at the
specified name, the existing end of the old file.
content will overwrite in a
file by
the given string.
Closing a File:

After completing our operations on the file, it is highly


recommended to close the file. For this we have to use
close() function.
f.close()
Various Properties of File Object:
Once we opened a file and we get file object, we can get various details

related to that file by using its properties.

Name : Name of opened file

Mode : Mode in which the file is opened

Closed : Returns boolean value indicates that file is closed or not

readable()àReturns boolean value indicates that whether file is readable or not

writable()-> Returns boolean value indicates that whether file is writable or not
Writing Data to Text Files: We can write character data to the text files by
using the following 2 methods.
1. write(str)
2. writelines(list of lines)
File Operations – tell() method
• tell() method returns the current position of the
file handle.
• Syntax:
file_object.tell()
File Operation – with/as method
• Syntax:
with file_creation as file_object:
block of statements
• Eg: output:
with open(“test.txt”) as f:
for line in f:
print(line.strip())
Format operator
• f.write(‘%s’ %‘Python’)  Prints Python to the
file
• f.write(‘%d %d %s’ %(3, 5,‘Values’))  Prints 3
5 Values to the file
• f.write(“I am studying %dst year in dept of %s at
%s college” %(1, ‘IT’, ‘KSRIET’))  Prints I am
studying 1st year in dept of IT at KSRIET
college to the file.
S.No Syntax Example Description

Writing a string into a


1 f.write(string) f.write("hello")
file.
f.writelines(“1st line \n second Writes a sequence of
2 f.writelines(sequence) line”) strings to the file.
f.read( ) #read entire file
To read the content of
3 f.read(size) f.read(4) #read the first 4 a file.
character
Reads one line at a
4 f.readline( ) f.readline( )
time.
Reads the entire file
5 f.readlines( ) f.readlines( ) and returns a list of
lines.
To flush the data
6 f.flush( ) f.flush( ) before closing any
file.
S.No Syntax Example Description

7 f.close( ) f.close( ) Close an open file.

f.name o/p: Return the name of


8 f.name the file.
1.txt

f.mode o/p: Return the Mode


9 f.mode of file.
w
import os
10 os.rename(old_name, Renames the file or
os.rename(“1.txt”, directory.
new name )
”2.txt” )
import os
Remove the file.
11 os.remove(file name) os.remove("2.txt")
Python Directories
• A directory or folder is a collection of files and sub-
directories(sub-folders).
• Again it is defined in ‘os’ module.
Methods Description Example

getcwd() Prints the current working directory os.getcwd()

chdir() Changes the current working directory os.chdir(‘C:\Users\’)


Lists all the files and sub-folders names
listdir() inside the CWD
os.listdir()

mkdir() Create a new directory os.mkdir(“Dir_Name”)


os.rename(“Dir_Name”,
rename() Rename a directory or a file “MyPrograms”)
remove() Deletes a file or a directory os.remove(“MyPrograms”)

rmdir() Removes an empty directory os.rmdir(“MyPrograms”)


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.
 argv[ ] is used to access the command line argument. The
argument list starts from 0.
 sys.argv[0]= gives file name
 sys.argv[1]=provides access to the first input
Example 1 output

addition of two num output

import sys
a= sys.argv[1]
sam@sam~$ python.exe sum.py
b= sys.argv[2]
sum=int(a)+int(b)
2 3 sum is 5
print("sum is",sum)
Errors and Exceptions
• Errors:

 mistakes in the program.

 Two types:
 Syntax Errors

 Run time errors

 Logical errors
Syntax Errors
• Also known as parsing errors.
• It is the common mistakes that we make while
typing the programs.
Exceptions
• Exceptions are unexpected events that occur during the
execution of a program.
• Mostly occurs due to logical mistakes.
• The python interpreter raises an exception if it encounters an
unexpected condition like running out of memory, dividing by
zero, etc.
• These exceptions can be caught and handled accordingly.
• If uncaught, the exceptions may cause the interpreter to stop
without any notice.
Errors
ZeroDivisionError

TypeError

ValueError

FileNotFoundError

EOFError

SleepingError

IndexError

KeyError
Error Example

a=int(input("Enter a number:"))
Exception Handling
 Exception handling is done by try and catch block.

Suspicious code that may raise an exception, this kind of code will be

placed in try block.

A block of code which handles the problem is placed in except block.

•try…except
•try…except…inbuilt exception
•try… except…else
•try…except…else….finally
•try.. except..except...
•try…raise..except..
try ... Except
• In Python, exceptions can be handled using a try statement.

1.A critical operation which can raise exception is placed inside the try clause
and the code that handles exception is written in except clause.
2.It is up to us, what operations we perform once we have caught the
exception.
3.Here is a simple example.
try…except …in built exception

Programmer is avoiding any damage that may happen to python program.


•try ... except ... else clause
1.Else part will be executed only if the try block doesn’t raise an exception.
try ... except …finally
A finally clause is always executed before leaving the try
statement, whether an exception has occurred or not.

Syntax
try:
code that create exception except:
exception handling statement else:
statements finally: statement
try …except…except… exception :

1.It is possible to have multiple except blocks for one try block.
Let us see Python multiple exception handling examples.

2.When the interpreter encounters an exception, it checks the


except blocks associated with that try block. These except
blocks may declare what kind of exceptions they handle. When
the interpreter finds a matching exception, it executes that
except block.
Example Program
try:
a=int(input("Enter a value:"))
except ValueError:
print("It is an string")
except KeyboardInterrupt:
print("Some other key is pressed here")
except IOError:
print("No input is given here")
OUTPUT:
Raising Exceptions

•In Python programming, exceptions are raised when


corresponding errors occur at run time, but we can forcefully raise
it using the keyword raise.

•It is possible to use the raise keyword without specifying what


exception to raise. Then, it realizes the exception that occurred.
This is why you can only put it in an except block.

Syntax:
>>> raise error name
Example: Output:

try: enter your


age=int(input("enter your age:")) age:-7 Age
if (age<0): can’t be
raise ValueError("Age can’t be negative") negative
except ValueError:
print("you have entered incorrect age")
else:
print("your age is:”,age)
Exceptions with Files
• If you try to open a file that doesn’t exist, you get an IOError:
>>> fin = open('bad_file')
IOError: [Errno 2] No such file or directory: 'bad_file'
• If you don’t have permission to access a file:
>>> fout = open('/etc/passwd', 'w')
PermissionError:[Errno 13] Permission denied: '/etc/passwd'
• And if you try to open a directory for reading, you get
>>> fin = open('/home')
IsADirectoryError: [Errno 21] Is a directory: '/home'
• To avoid these errors, you could use functions like
os.path.exists and os.path.isfile
Modules and Packages
Modules
• Similar programs can be grouped together into a
module and written as separate functions in it.
• It would be easier to refer to multiple functions
together as a module.
• Modules can be used in a program using ‘import’
statement.
• A module allows us to logically organize a python
code.
calci.py
def add(a,b): def sub(a,b): def pdt(a,b): def div(a,b):
c=a+b c=abs(a-b) c=a*b c=a/b
print(c) print(c) print(c) print(c)

def
floordiv(a,b):
c=a//b
print(c)

• These functions are written together in a single


python program as calci.py
import calci Calculator.py – import
a=int(input(“Enter a number”))
statement
b=int(input(“Enter a number”))
print(“1. add 2. sub 3.product 4.division 5. floor division 6. modulo 7. exponentiation”)
ch=int(input(“Enter your choice of operation:”))
if(ch==1):
calci.add(a,b)
elif(ch==2):
calci.sub(a,b)
elif(ch==3):
calci.pdt(a,b)
elif(ch==4):
calci.div(a,b)
elif(ch==5):
calci.floordiv(a,b)
else:
break
print(“Thanks for using our aplication!!”)
import with renaming
Eg:
import math as a
print(“The value of pi is :”, a.pi)

Output:
The value of pi is : 3.141592653589793
from … import statement
• Python’s from statement helps to import specific
attributes from a module into the current program.
• Syntax:
from modulename import name1[,name2,
…]
• Eg:
from calci import add, sub
• Here only the add and sub functions alone are
imported from calci module instead of entire module.
• Also from calci import * can be used to import all
functions to the python program.
PACKAGES
• A package is a collection of python modules.
• Eg: Pygame, Turtle, etc,.
• These are the separate software packages that can
be imported into our python program.
• These packages in turn contains several modules to
produce the expected results.
Step 1: Create the Package Directory
Step 2: write Modules for calculator directory
add save the modules in calculator directory.
Step 3 :Add the following code in the
_init_.py file
Step 4: To test your package
ILLUSTRATIVE PROGRAMS
Word count Output
import sys
a = argv[1].split() C:\Python34>python .exe word.py
dict = {} "python is awesome lets
for i in a: program in python"
if i in dict: {'lets': 1, 'awesome': 1, 'in': 1,
dict[i]=dict[i]+1 'python': 2,
else: 'program': 1, 'is': 1}
dict[i] = 1 7
print(dict)
print(len(a))
Copy a file Output
f1=open("1.txt","r") no output
f2=open("2.txt“,w") internally the content in f1
for i in f1: will be copied to f2
f2.write(i)
f1.close()
f2.close()
copy and display contents Output
f1=open("1.txt","r") hello
f2=open("2.txt","w+ welcome to python
") for i in f1: programming
f2.write(i)
f2.seek(0) (content in f1 and f2)
print(f2.read())
f1.close()
f2.close()
Voters Age Validation

try:
age=int(input(“Enter Your Age:”))
if age>18:
print(“Eligible to vote!!!”)
else:
print(“Not eligible to vote!!!”)
exceptValueError as err:
print(err)
finally:
# Code to be executed whether exception occurs or not
# Typically for closing files and other resources
print(“Good Bye!!!”)
• Output1:
• Enter Your Age: 20
• Eligible to vote!!!
• Good Bye!!!

• Output2:
• Enter Your Age: 16
• Not eligible to vote!!!
• Good Bye!!!
Marks Range Validation (0-100)

whileTrue:
try:
num = int(input("Enter a number between 1 and 100:
"))
if num in range(1,100):
print("Valid number!!!")
break
else:
print (“Invalid number. Try again.”)
except:
print (“That is not a number. Try”)
Output:
Enter a number between 1 and 100: -1
Invalid number.
Try again.
Enter a number between 1 and 100: 1000
Invalid number.
Try again.
Enter a number between 1 and 100: five
This is not a number. Try again.
Enter a number between 1 and 100: 99
Valid number!!!

You might also like