1. 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
UNIT 5
FILES, MODULES AND PACKAGES
2. 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.
3. 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...
4. Text
File
Binary
File
Text file is a sequence of
characters that can be
sequentially processed by a
computer in forward direction.
A binary files store the data in
the binary format (i.e. 0’s and
1’s )
Each line is terminated with a
special character, called the EOL
or End of Line character
It contains any type of data
( PDF , images , Word
doc,Spreadsheet, Zip files,etc)
5. 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.
6. 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
7. Mode Name
r read only mode
w write only
a appending mode
r+ read and write mode
w+ write and read mode
Modes in file:
8. Differentiate write and append mode:
Write Mode Append Mode
It is use to write a string
into a file.
It is used to append (add) a
string into a file.
If file does not exist it
creates a new file
If file does not exist it
creates a new file.
If file is exist in the
specified name, the existing
content will overwrite in a
file by
the given string.
It will add the string at the
end of the old file.
9. 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()
10. 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
12. 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)
15. File Operations – tell() method
• tell() method returns the current position of the
file handle.
• Syntax:
file_object.tell()
17. 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())
19. 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.
20. S.No Syntax Example Description
1 f.write(string) f.write("hello")
Writing a string into a
file.
2 f.writelines(sequence)
f.writelines(“1st line n second
line”)
Writes a sequence of
strings to the file.
3 f.read(size)
f.read( ) #read entire file
f.read(4) #read the first 4
character
To read the content of
a file.
4 f.readline( ) f.readline( )
Reads one line at a
time.
5 f.readlines( ) f.readlines( )
Reads the entire file
and returns a list of
lines.
6 f.flush( ) f.flush( )
To flush the data
before closing any
file.
21. S.No Syntax Example Description
7 f.close( ) f.close( ) Close an open file.
8 f.name f.name o/p:
1.txt
Return the name of
the file.
9 f.mode f.mode o/p:
w
Return the Mode
of file.
10 os.rename(old_name,
new name )
import os
os.rename(“1.txt”,
”2.txt” )
Renames the file or
directory.
11 os.remove(file name)
import os
os.remove("2.txt")
Remove the file.
22. 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’)
listdir()
Lists all the files and sub-folders names
inside the CWD
os.listdir()
mkdir() Create a new directory os.mkdir(“Dir_Name”)
rename() Rename a directory or a file
os.rename(“Dir_Name”,
“MyPrograms”)
remove() Deletes a file or a directory os.remove(“MyPrograms”)
rmdir() Removes an empty directory os.rmdir(“MyPrograms”)
23. 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
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.
24. Example 1 output
addition of two num output
import sys
a= sys.argv[1]
b= sys.argv[2]
sum=int(a)+int(b)
print("sum is",sum)
sam@sam~$ python.exe sum.py
2 3 sum is 5
25. Errors and Exceptions
• Errors:
mistakes in the program.
Two types:
Syntax Errors
Run time errors
Logical errors
26. Syntax Errors
• Also known as parsing errors.
• It is the common mistakes that we make while
typing the programs.
27. 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.
34. 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..
35. 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.
36. try…except …in built exception
Programmer is avoiding any damage that may happen to python program.
37. •try ... except ... else clause
1.Else part will be executed only if the try block doesn’t raise an exception.
38. 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
40. 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.
41. 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:
42. 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
43. Example: Output:
try:
age=int(input("enter your age:"))
if (age<0):
raise ValueError("Age can’t be negative")
except ValueError:
print("you have entered incorrect age")
else:
print("your age is:”,age)
enter your
age:-7 Age
can’t be
negative
44. 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
46. 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.
47. calci.py
• These functions are written together in a single
python program as calci.py
def add(a,b):
c=a+b
print(c)
def sub(a,b):
c=abs(a-b)
print(c)
def div(a,b):
c=a/b
print(c)
def pdt(a,b):
c=a*b
print(c)
def
floordiv(a,b):
c=a//b
print(c)
48. Calculator.py – import
statement
import calci
a=int(input(“Enter a number”))
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!!”)
49. import with renaming
Eg:
import math as a
print(“The value of pi is :”, a.pi)
Output:
The value of pi is : 3.141592653589793
50. 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.
52. 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.
58. Word count Output
import sys
a = argv[1].split()
dict = {}
for i in a:
if i in dict:
dict[i]=dict[i]+1
else:
dict[i] = 1
print(dict)
print(len(a))
C:Python34>python .exe word.py
"python is awesome lets
program in python"
{'lets': 1, 'awesome': 1, 'in': 1,
'python': 2,
'program': 1, 'is': 1}
7
59. Copy a file Output
f1=open("1.txt","r")
f2=open("2.txt“,w")
for i in f1:
f2.write(i)
f1.close()
f2.close()
no output
internally the content in f1
will be copied to f2
60. copy and display contents Output
f1=open("1.txt","r")
f2=open("2.txt","w+
") for i in f1:
f2.write(i)
f2.seek(0)
print(f2.read())
f1.close()
f2.close()
hello
welcome to python
programming
(content in f1 and f2)
61. 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!!!”)
62. • Output1:
• Enter Your Age: 20
• Eligible to vote!!!
• Good Bye!!!
•
• Output2:
• Enter Your Age: 16
• Not eligible to vote!!!
• Good Bye!!!
63. 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”)
64. 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!!!