Python Unit 4
Python Unit 4
Python Programming
Unit IV
Unit IV: FILES, MODULES,
Programming
PACKAGES
Python
Handling exceptions
utilizing the data structures like lists, dictionaries, tuples and sets.
29-03-2022 5
Files
• File is a named location on disk to store related information.
• File is used to permanently store data in a non-volatile memory (e.g. hard disk).
for future use.
• To read or write, file is to be open, when done it need to be saved & closed,
Programming
so that resources that are tied with the file are freed.
• Hence, in Python, a file operation takes place in the following order.
Python
1. Open a file
2. Read or write (perform operation)
3. Close the file
• 'x' : Open a file for exclusive creation. If the file exists, the operation fails.
• 'a' : Open for appending at the end of the file without truncating it. Creates a
Python
• If the file existing, Careful - opening in write mode clears out the old data
and starts fresh
out.write(line2)
fout.close() # close the file.
a file.
If file does not exist it creates a new If file does not exist it creates a new
file. file.
Python
If file is exist in the specified name, It will add the string at the end of the old
the existing content will be file.
overwritten by the given string.
file = open('sample.txt','w')
file.write("hello")
Python
file.close()
file1.writelines(L)
file1.close()
Python
file1.seek(0)
Python
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
file1.close()
fout.write(str(x))
• Alternative way 1: Use the format operator, %
Python
camels = 42
'%d' % camels
Python
• The result is the string '42', which is not to be confused with the integer
value 42.
First
Result : 'I have spotted
Operand 42 camels.'
Python
• If there is more than one format sequence in the string, the second
argument has to be a tuple.
• Each format sequence is matched with an element of the tuple, in order.
VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa
www.damodarcollege.edu.in
Formatting using format operator
• Example: Using '%d' to format an integer, '%g’ to format a floating-point
number and '%s' to format a string:
'In %d years I have spotted %f %g.' % (3, 0.1, 'camels')
'In 3 years I have spotted 0.1 camels.'
Programming
• The number & types of tuple elements has to match with that of format
sequences in the string:
Python
'%d %d %d' % (1, 2) # TypeError: not enough arguments for format string
'%d' % 'dollars' # TypeError: illegal argument type for built-in
operation
directory.
• Use os module provides functions for working with files and directories (“os”
stands for “operating system”).
Python
'/home/dinsdale/memo.txt'
• os.path.exists() checks whether a file or directory exists:
os.path.exists('memo.txt') output: True
• os.path.isdir() checks whether it’s a directory:
os.path.isdir('memo.txt') output: False
VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa
www.damodarcollege.edu.in
Filenames and Paths
• os.path.isdir() checks whether it’s a directory:
os.path.isdir('memo.txt') output: False
os.path.isdir('music') output: True
• os.path.isfile() checks whether it’s a file.
Programming
• os.listdir() returns a list of the files (and directories) in the given directory
Python
print path
else:
walk(path)
argv[ ] is used to access the command line argument. The argument list starts
from 0. In argv[ ], the first argument always the file name
sys.argv[0] gives file name
sys.argv[1] provides access to the first input
VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa
www.damodarcollege.edu.in
Command Line Argument
• Example 1:
import sys
print( “file name is %s” %(sys.argv[0]))
• Example 2:
Programming
import sys
Python
a= sys.argv[1]
b= sys.argv[2]
sum=int(a)+int(b)
print("sum is",sum)
for i in a:
if i in dict:
Python
dict[i]=dict[i]+1
else:
dict[i] = 1
print(dict)
print(len(a))
1. Syntax errors
2. Runtime errors
3. Logical errors
Python
division by zero
performing an operation on incompatible types
using an identifier which has not been defined
accessing a list element, dictionary value or object attribute which does not exist
trying to access a file which does not exist
• Example
• When a file we try to open does not exist (FileNotFoundError)
• Dividing a number by zero (ZeroDivisionError)
• Module we try to import is not found (ImportError) etc.
2. try…except…inbuilt exception
3. try… except…else
4. try…except…else….finally
5. try…raise..except..
• Syntax
try:
Python
try:
code that create exception
except inbuilt exception:
exception handling statement
try:
code that create exception
raise exception
Python
except:
exception handling statement
else:
statements
29-03-2022 48
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.
Programming
• Standard modules can be imported the same way as we import our user-
defined modules. We use:
1. import keyword
2. from keyword
import module_name
module_name.function_name(variable)
print(x)
• Importing user defined module:
Python
import cal
x=cal.add(5,4)
print(x)
Examples:
• Importing builtin module • Importing user defined module
Python
Illustrative Programmes
29-03-2022 63
1. Program to copy from one file to another
fs=open("First.txt","r")
fd=open("Dest.txt","w")
fdata = fs.read()
Programming
fd.write(fdata)
print("File copied sucessfully!!!")
Python
fs.close()
fd.close()
count=0
for i in L:
Python
count=count+1
print("Total no of words in the file: ",count)
fs.close()
raise ValueError
elif (Age>=18):
print(Name, " is eligible for voting.")
Python
else:
print(Name," is not Eligible for voting.")
except (ValueError):
print("Value Error: invalid Age value.")
raise ValueError
if (all(m>=50 for m in marklist)):
print(Name, "- Grade - Pass.",end=" ")
print("Total = ", sum(marklist),end=" ")
Python
print("Average = ",round((sum(marklist)/len(marklist)),2))
break
else:
print(Name, "- Grade - Fail.")
break
except (ValueError):
print("Value Error: invalid mark.")
End of Unit IV
Thank You
Python
08/07/2025 VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa 68
www.damodarcollege.edu.in