0% found this document useful (0 votes)
0 views68 pages

Python Unit 4

This document outlines Unit IV of a Python Programming course at Shree Damodar College of Commerce & Economics, covering files, modules, and packages. It includes topics such as file operations, exception handling, and formatting data, alongside learning outcomes and illustrative programming examples. The document also provides practical exercises for students to practice file handling in Python.

Uploaded by

sharada k
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)
0 views68 pages

Python Unit 4

This document outlines Unit IV of a Python Programming course at Shree Damodar College of Commerce & Economics, covering files, modules, and packages. It includes topics such as file operations, exception handling, and formatting data, alongside learning outcomes and illustrative programming examples. The document also provides practical exercises for students to practice file handling in Python.

Uploaded by

sharada k
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/ 68

Vidya Vikas Mandal’s

SHREE DAMODAR COLLEGE OF COMMERCE & ECONOMICS


Affiliated to Goa University
Accredited by NAAC with Grade ‘A’

Python Programming
Unit IV
Unit IV: FILES, MODULES,
Programming

PACKAGES
Python

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Outline
• Files and exception
• Text files
• Reading and writing files, format operator
Programming

• Command line arguments


• Errors and exceptions,

Python

Handling exceptions

• Modules & Packages


• Illustrative programs: word count, copy file.

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Learning Outcomes
CO1. Explain fundamental principles, syntax and semantics of Python
programming.
CO2. Demonstrate the understanding of program flow control and handling of
Programming

strings, functions, files & exception handling.


CO3. Determine the methods to create and develop Python programs by
Python

utilizing the data structures like lists, dictionaries, tuples and sets.

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Vidya Vikas Mandal’s
SHREE DAMODAR COLLEGE OF COMMERCE & ECONOMICS
Affiliated to Goa University
Accredited by NAAC with Grade ‘A’

Files and Exception

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

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Opening a file
• Use built-in function open() to open a file
• It returns a file object, also called a handle, as it is used to read or modify
the file accordingly.
Programming

f = open("test.txt") # open file in current directory


f = open("C:/Python33/README.txt") # specifying full path
Python

• We can specify the mode while opening a file.


• In mode use ‘r’ to read or ‘w’ to write or ‘a’ to append to the file
• Can also specify if file to be opened in text mode or binary mode.

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Opening a file
• The default is reading in text mode and we get strings when reading from
the file.
• Binary mode returns bytes and is used when dealing with non-text files like
image or exe files.
Programming
Python

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Python File Modes
• 'r' : Open a file for reading. (default)
• 'w' : Open a file for writing. Creates a new file if it does not exist or truncates
the file if it exists.
Programming

• '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

new file if it does not exist.


• 't' : Open in text mode. (default)
• 'b' : Open in binary mode.
• '+' : Open a file for updating (reading and writing)
VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa
www.damodarcollege.edu.in
Python File Modes
f = open("test.txt") # equivalent to 'r' or 'rt'
f = open("test.txt",'w') # write in text mode
f = open("img.bmp",'r+b') # read and write in binary mode
Programming

• When working with files in text mode, it is highly recommended to specify


Python

the encoding type.


f = open("test.txt",mode = 'r',encoding = 'utf-8')

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Closing a File
• Properly closing a file will free up the resources tied with the file using
close() method.
f = open("test.txt",encoding = 'utf-8') # perform file
operations
Programming

f.close() # This method is


not entirely safe.
• If an exception occurs, the code exits without closing the file
Python

• A safer way is to use a try...finally block.


try:
f= open("test.txt",encoding = 'utf-8') # perform file operations
finally:
f.close()
It guarantees proper closer of file even if an exception is raised.
VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa
www.damodarcollege.edu.in
Reading and writing
• A text file is a sequence of characters stored
• To write a file, open with mode 'w' as a second parameter:
fout = open('output.txt', 'w')
print fout
Programming

Output: <open file 'output.txt', mode 'w' at 0xb7eb2410>


• If the file doesn’t exist, a new one is created.
Python

• If the file existing, Careful - opening in write mode clears out the old data
and starts fresh

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Reading and writing
• The write method puts data into the file.
line1 = "This here's the wattle,\n"
fout.write(line1)
• The file object keeps track of where it is, so if you call write again, it adds
Programming

the new data to the end.


line2 = "the emblem of our land.\n"
Python

out.write(line2)
fout.close() # close the file.

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Formatting
• Differentiate write and append mode

write mode append mode


It is used to write a string into a file. It is used to append (add) a string into
Programming

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.

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Programming
Python

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Programming
Python

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Examples to Practice in Lab
• Program 1: Opening and Closing a file "MyFile.txt
file1 = open("MyFile.txt","a")
file1.close()

• Program 2: To create a text file by name sample and text is written to it


Programming

file = open('sample.txt','w')
file.write("hello")
Python

file.close()

• Program 3: To read and content displayed


file = open('sample.txt','r')
print(file.read()) # read the file sample and diplay the output
file.close()

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Examples to Practice in Lab
• Program 4: Program to show various ways to read and write data in a file.
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]
file1.write("Hello \n")
Programming

file1.writelines(L)
file1.close()
Python

#to change file access modes


file1 = open("myfile.txt","r")
print("Output of Read function is ")
print(file1.read())

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Examples to Practice in Lab
# seek(n) takes the file handle to the nth byte from the beginning.
file1.seek(0)
print( "Output of Readline function is ")
print(file1.readline())
Programming

file1.seek(0)
Python

# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
file1.close()

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Formatting
• The argument of write has to be a string
• Values of other type to be converted into String and then write in file.
• The easiest way to do that is with str:
x = 52
Programming

fout.write(str(x))
• Alternative way 1: Use the format operator, %
Python

 When applied to integers, % is the modulus operator.


 But when the first operand is a string, % is the format operator.

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Formatting using format operator
• The first operand is the format string, which contains one or more format
sequences, which specify how the second operand is formatted.
• For example: format sequence '%d' means that the second operand should
be formatted as an integer (d stands for “decimal”):
Programming

camels = 42
'%d' % camels
Python

• The result is the string '42', which is not to be confused with the integer
value 42.

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Formatting using format operator
• A format sequence can appear anywhere in the string, so you can embed a
value in a sentence:
Second
camels = 42 Operand

'I have spotted %d camels.' % camels


Programming

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

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Programming Formatting using format operator
Python

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Formatting using format() method
• Alternative Way 2: Use .format() method
• The .format() method formats the specified values and insert them inside
the string's placeholder.
• The placeholder is defined using curly brackets { }. Examples:
Programming

print("My name is {}, I'm {}".format("John",36))


output : My name is John, I'm 36
Python

print("My name is {fname}, I'm {age}".format(fname = "John", age =


36))
output: My name is John, I'm 36
print("My name is {0}, I'm {1}".format("John",36))
output : My name is John, I'm 36
VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa
www.damodarcollege.edu.in
Formatting in Files
• The argument of write() has to be a string, so if we want to put other values
in a file, we have to convert them to strings.
• Use any of the 3 methods expalined earlier
Programming
Python

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Filenames and Paths
• Files are organized into directories (also called “folders”).
• Every running program has a “current directory,” which is the default
directory for most operations.
• Example, when you open a file for reading, Python looks for it in the current
Programming

directory.
• Use os module provides functions for working with files and directories (“os”
stands for “operating system”).
Python

os.getcwd returns the name of the current directory:


import os
cwd = os.getcwd() #cwd stands for “current working
directory.”
print cwd /home/dinsdale
# /home/dinsdale, is the home directory of a user named dinsdale.
VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa
www.damodarcollege.edu.in
Filenames and Paths
• A relative path starts from the current directory
• An absolute path starts from the topmost directory in the file system.
• The paths we have seen so far are simple filenames, so they are relative to
the current directory.
Programming

• To find the absolute path to a file, use os.path.abspath(). Example


os.path.abspath('memo.txt') output:
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

os.listdir(cwd) output: ['music',


'photos', 'memo.txt']
• os.path.join() takes a directory and a file name and joins them into a
complete path.

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Filenames and Paths
• Demo Function: Below function “walks” through a directory, prints the
names of all the files, and calls itself recursively on all the directories.
def walk(dirname):
for name in os.listdir(dirname):
Programming

path = os.path.join(dirname, name)


if os.path.isfile(path):
Python

print path
else:
walk(path)

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Command Line Argument
• The command line argument is used to pass input from the command line
to the program when the program is executed.

• Handling command line arguments with Python need sys module.


Programming

• sys module provides information about constants, functions and methods


of the python interpreter.
Python

 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)

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Command Line Argument
• Example 3: Word occurrence count using command line arg:
from sys import argv
a = argv[1].split()
dict = {}
Programming

for i in a:
if i in dict:
Python

dict[i]=dict[i]+1
else:
dict[i] = 1
print(dict)
print(len(a))

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Errors & Exception - Errors
• Errors are the mistakes in the program also referred as bugs.
• The process of finding and eliminating errors is called debugging.
• Errors can be classified into three major groups:
Programming

1. Syntax errors
2. Runtime errors
3. Logical errors
Python

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Errors & Exception - Errors
1. Syntax Errors
• Errors that occurs due wrong syntax used by the programmer. When a
program has syntax errors it will not get executed.
• Common Python syntax errors include:
Programming

 leaving out a keyword


 putting a keyword in the wrong place
Python

 leaving out a symbol, such as a colon, comma or brackets


 misspelling a keyword
 incorrect indentation
 empty block

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Errors & Exception - Errors
2. Runtime Errors
• If a program 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.
Programming

• In case of runtime error, program will not produce output.


 Common Python runtime errors include
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

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Errors & Exception - Errors
3. Logical Errors
• Logical errors occur due to wrong program logic, and are difficult to fix.
• Here program runs without any error but produces an undesired result.
• Common Python logical errors include
Programming

a. using the wrong variable name


b. indenting a block to the wrong level
Python

c. using integer division instead of floating-point division


d. getting operator precedence wrong
e. making a mistake in a boolean expression

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Errors & Exception - Exception
• An exception (runtime time error) is an error, that 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
Programming

exception immediately otherwise it terminates or quit.


Python

• 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.

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Errors & Exception - Exception
• Whenever these type of runtime error occur
• Python creates an exception object.
• If not handled properly, it prints a traceback to that error along with some details about
why that error occurred.
Programming
Python

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Programming
Python

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Programming
Python

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Handling Exception
• Exception handling is done by try and except 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.
Programming

• If an error is encountered, a try block code execution is stopped and control


transferred down to except block
1. try…except
Python

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

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Handling Exception
1. try ... except
• First try clause is executed. if no exception occurs, the except clause is
skipped and execution of the try statement is finished.
• If an exception occurs during execution of the try clause, the rest of the try
clause is skipped.
Programming

• Syntax
try:
Python

code that create exception


except:
exception handling statement

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Handling Exception
2. try…except…inbuilt exception
• First try clause is executed. if no exception occurs, the except clause is
skipped and execution of the try statement is finished.
• if exception occurs and its type matches the exception named after the
except keyword, the except clause is executed and then execution
Programming

continues after the try statement


• Syntax
Python

try:
code that create exception
except inbuilt exception:
exception handling statement

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Handling Exception
3. try…except…else clause
• Else part will be executed only if the try block does not raise an exception.
• Python will try to process all the statements inside try block.
• If error occurs, the flow of control will immediately pass to the except block and
Programming

remaining statement in try block will be skipped.


• Syntax
try:
Python

code that create exception


except:
exception handling statement
else:
statements
VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa
www.damodarcollege.edu.in
Handling Exception
4. try…except…finally
• A finally clause is always executed before leaving the try statement, whether an
exception has occurred or not.
• Syntax
try:
Programming

code that create exception


except:
Python

exception handling statement


else:
statements
finally:
statements

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Handling Exception
4. try…raise...except (Raising Exceptions)
• In Python programming, exceptions are raised when corresponding errors occur at
runtime, but we can forcefully raise it using the keyword raise.
• Syntax
Programming

try:
code that create exception
raise exception
Python

except:
exception handling statement
else:
statements

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Vidya Vikas Mandal’s
SHREE DAMODAR COLLEGE OF COMMERCE & ECONOMICS
Affiliated to Goa University
Accredited by NAAC with Grade ‘A’

Modules & Packages

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

• Once we import a module, we can reference or use to any of its functions or


variables in our code.
• There is large number of standard modules also available in python.
Python

• Standard modules can be imported the same way as we import our user-
defined modules. We use:
1. import keyword
2. from keyword

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Modules
1) import keyword
• import keyword is used to get all functions from the module.
• Every module contains many function.
• To access one of the function, need to specify the module name and the
Programming

function name separated by dot. This format is called dot notation.


• Syntax:
Python

import module_name
module_name.function_name(variable)

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Modules
Examples:
• Importing builtin module
import math
x=math.sqrt(25)
Programming

print(x)
• Importing user defined module:
Python

import cal
x=cal.add(5,4)
print(x)

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Modules
2) from keyword:
• from keyword is used to get only one particular function from the module.
• Syntax:
from module_name import function_name
Programming

Examples:
• Importing builtin module • Importing user defined module
Python

from math import sqrt from cal import add


x=sqrt(25) x=add(5,4)
print(x) print(x)

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Programming
Python

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
• OS module
• Provides functions for interacting with the operating system
• To access the OS module have to import the OS module in our program
import os
Programming
Python

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
• sys module
• sys module provides information about constants, functions and methods.
• It provides access to some variables used or maintained by the interpreter.
import sys
Programming
Python

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
• Steps to create the own module
• Here we are going to create calc module: our module contains four
functions they are add(),sub(),mul(),div()
Programming
Python

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Packages
• A package is a collection of Python modules.
• Module is a single Python file containing function definitions
• A package is a directory (folder) of Python modules containing an additional
Programming

__init_.pyfile, to differentiate a package from a directory.


• Packages can be nested to any depth, provided that the corresponding
Python

directories contain their own __init__.py file.


• __init__.py file is a directory indicates to the python interpreter that the
directory should be treated like a python package.__init__.py is used to
initialize the python package.

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Packages
• A package is a hierarchical file directory
structure that defines a single python
application environment that consists of
Programming

modules, sub packages, sub-sub packages


and so on.
Python

• __init__.py file is necessary since Python will


know that this directory is a python package
directory other than ordinary directory

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Packages
• Steps to create a package
Step 1: Create the Package Directory: Create a directory (folder)
and give it your package's name. Here the package name is calculator.
Programming
Python

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Packages
Step 2: Write Modules for calculator directory add save the modules in
calculator directory.
Here four modules have created for calculator directory.
Programming
Python

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Packages
Step 3: Add the __init__.py File in the calculator directory. A directory
must contain a file named _init_.py in order for Python to consider it as a
package. Add the following code in the __init__.py file.
from . add import add
Programming

from . sub import sub


from . mul import mul
from . div import div
Python

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Packages
Step 4: To test your package in your program and add the path of your
package in your program by using sys.path.append().
Here the path is C:\python34
Programming
Python

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Vidya Vikas Mandal’s
SHREE DAMODAR COLLEGE OF COMMERCE & ECONOMICS
Affiliated to Goa University
Accredited by NAAC with Grade ‘A’

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()

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
2. Program to count no of words in a file
fs = open("First.txt","r")
fdata = fs.read()
L = fdata.split()
Programming

count=0
for i in L:
Python

count=count+1
print("Total no of words in the file: ",count)
fs.close()

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
3. Program to validate Voter’s age
try:
Name = input("Enter name : ")
Age = int(input("Enter Age : "))
if(Age<0):
Programming

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.")

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
4. Program to validate Student’s mark Range (0-100)
try:
L = ["AAA",100,30,80,90,50]
Name = L[0]
marklist = [int(m) for m in L[1:]]
for mark in marklist:
if(mark<0 or mark>100):
Programming

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.")

VVM’s Shree Damodar College of Commerce and Economics, Margao – Goa


www.damodarcollege.edu.in
Programming

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

You might also like