Python Programming
UNIT-V
Files and Exceptions:
Text files: A text file in python is a file that stores data in plain text (human- readable) format.
• It uses characters like letters, numbers, and symbols.
• The content inside a text file is encoded using ASCII or UTF-8.
• File extension is usually .txt.
Examples of Text Files:
• notes.txt, data.txt.
Characteristics of Text Files:
1. Readable by humans (you can open it in Notepad, VS code, etc.).
2. Stores data line by line using newline characters.
3. Takes more storage compared to binary files for the same data.
4. Easy to edit and share.
• Working with Text files in python:
Python provides the open () function to handle text files.
Ex :- Writing to a text file:
with open ("example.txt", "w") as f:
f.write ("Hello, this is a text file in Python.\n")
f.write ("It stores data as plain text.")
Ex :- Reading from a text file:
with open ("example.txt", "r") as f:
data = f.read ()
print(data)
Reading and Writing Text Files in Python
1. Introduction:
- A file is used to store data permanently on a disk.
- Python provides simple functions to read from and write to text files.
- The built-in function open () is used to work with files.
2. Opening a File:
Opening a file in python means creating a connection between a python program and an
external file (such as a text file) so that the program can read data from or write data into the
file.
Syntax: file_object = open (“filename”, “mode”)
1
Python Programming
• “filename”->name of the file (e.g., ”data.txt”)
• “mode” ->tells python what action to perform (read, write, append, etc.)
3. Writing to a File:
Writing to a file in python means the process of storing data from a python program into a file
(usually a text file) on the disk, so that the data can be saved permanently.
file_object=open (“file name”, ” w”)
file_object.write (“more data”)
file_object.close ()
4. Reading from a File :
Reading from a file in python means the process of retrieving or accessing data stored in a file
and making it available to the python program for further use.
It is done by opening the file in read mode (“r”) and using methods like read(), readline(),
readlines()
Ex: # Open file in read mode
file_object = open ("filename.txt", "r")
# Read data from file
data = file_object.read() # reads entire file
line = file_object.readline() # reads one line
lines = file_object.readlines() # reads all lines into a list
file_object.close() # Close the file
5. Appending to a File :
“Appending to a file in python means adding new data at the end of an existing file without
erasing its previous contents.
It is done by opening the file in append mode (“a”).
Ex: # Open file in append mode
file_object = open("filename.txt", "a")
# Add new data at the end of file
file_object.write("This is new data\n")
file_object.close() # Close the file
2
Python Programming
Format operator:
In Python, the format operator (%) is used for string formatting, often called "printf-style"
formatting. It allows you to insert values into strings using format specifiers.
Syntax:
formatted_string = "format string with % placeholders" % values
Common Format Specifiers
Specifier Description Example
%s String “Hello %s” %” World”
%d Integer “Age: %d” % 25
%f Float “Price: %.2f” % 19.99
%x Hexadecimal “Hex: %x” % 255
%o Octal “Oct: %o” % 64
%% Literal % “Discount: 10%%”
Examples
1.Single Value Formatting:
Single value formatting in python means inserting one value into a string at a specific
placeholder using the format specifiers or formatting methods.
Ex :
name = "Sania"
print ("Hello %s" % name) # %s → string placeholder
output: Hello Sania
2.Multiple Values Formatting:
Multiple value formatting in python means inserting more than one values into a string at
different placeholders.
Ex: name = "Sania"
age = 20
marks = 95.6
print("Name: %s, Age: %d, Marks: %.1f" % (name, age, marks))
output: Name: Sania, Age: 20, Marks: 95.6
3
Python Programming
3.Float Formatting with Precision:
Float formatting with precision in python means controlling the number of digits shown after
the decimal point when printing or displaying floating-point numbers.
Ex:
num = 12.34567
print("Value = {:.3f}".format(num)) # 3 decimal places
Output:
Value = 12.346
Padding and Alignment:
# Right align with padding
message = "%10s" % "hello"
print (message)
Output: " hello"
# Left align with padding
message = "%-10s" % "hello"
print(message)
Output: "hello "
When to Use % Formatting
· Working with legacy code
· Simple formatting needs
· When you need specific printf-style formatting
· When compatibility with older Python versions is required
4
Python Programming
Errors:
•Errors are problems in a program that stops execution.
•They usually happen because of wrong syntax, invalid code, or logical mistakes.
•Errors are two types :
a. Syntax Erors
b. Logical Errors
1) Syntax Error:
Occur when python cannot understand the code because it breaks the language rules.
2) Logical Error:
Code runs without crashing, but output is wrong due to incorrect logic.
Exception:
Exceptions are runtime error that occur when the code is syntactically correct, but
something unexpected happens during execution.
Common Exceptions:
Sr.no Name of the Exception Description of the Exception
1 StandardError Excluding the StopIteration and SystemExit, this is the
base class for all python built-in exceptions.
2 ZeroDivisorError For all numeric data types, its value is raised whenever
a number is attempted to be divided by zero.
3 IndexError This exception is raised when the index attempted to
be accessed is not found.
4 NameError This exception raised when a variable isn’t located in
either local or global namespace.
5 TypeError This exception is raised if the parameters for a built-in
method for a particular data type are the correct type
but have been given the wrong values.
Exception Handling in python:
Handling Exception:
• If an exception occurs, the program stops suddenly.
• To avoid crashing, we use exception handling.
• It allows the program to detect error and continue running safely.
In Python we can handle the exception by using try block, and except block.
5
Python Programming
Syntax:
try:
statement block
except (exception name):
Statement block
try:- Code that might cause an exception.
except:- Code that runs when an exception occurs.
Ex:- Program to handle the ZeroDivisionError
n=int(input(“enter a number:”))
demo=int(input(“enter denominator value:”))
try:
d=n/demo
print(“value=”, d)
except ZeroDivisonError:
print (“denominator is zero, cannot divided”)
using finally:
• The finally block always executes, whether there is an error or not.
Ex :-
try: # Code that might cause an error
num = int (input("Enter a number: "))
result = 10 / num
print ("Result:", result)
except ZeroDivision : # This block runs if number = 0
print(" Cannot divide by zero")
except ValueError: # This block runs if input is not a number
print(“ Please enter a valid number")
finally: # This block always executes
print ("Program finished (finally block executed)")
6
Python Programming
Multiple Exceptions :-
Python allows you to have multiple except blocks for a single try block. The block
which matches with the exception generated will get executed.
Syntax:
try:
statement
except exception 1:
statement
except exception 2:
statement
else:
statement
Example:- program to demonstrate the concept of multiple except block
try:
n=int (input ("enter n values":))
print(n**3)
except (KeyboardInterrupt):
print("you have to check your input")
except(ValueError):
print("enter only number")
else:
print ("check your program")
Raised Exceptions:
• In python exceptions are usually raised automatically when something
goes wrong (e.g., divide by zero).
• But sometimes we want to manually create(raise) an exception when a
certain condition is not acceptable.
• We use the raise keyword for this.
Syntax:
raise[exception,[arguments]]
Ex:-for exception raising
try:
num = int(input("Enter a positive number: "))
if num <= 0:
raise ValueError(“ Number must be positive")
print(" You entered:", num)
except ValueError as e:
print("Error occurred:", e)
7
Python Programming
Handling Exceptions in Functions:
• Functions often perform specific tasks (like dividing numbers,
opening files, etc.)
• If something goes wrong inside a function (like invalid input),
exceptions may occur.
• By handling exceptions inside the function, we can prevent the
whole program from crashing.
Ex:- program to handle exception in the calling function
def divide(n1,n2):
return n1/n2
try:
divide(10,0)
except ZeroDisionError:
print(“you cannot divide a number by zero”)
Raising Exception from a Function:
Sometimes we want a function to raise an exception instead of handling it, so the caller can
decide.
Ex:-
def check_age(age):
if age < 18:
raise ValueError("Age must be at least 18")
return "Access granted"
try:
print(check_age(15))
except ValueError as e:
print("Error:", e)
8
Python Programming
Modules:
In Python, a module is a file containing Python definitions and statements. Essentially, any
Python file saved with a .py extension can be considered a module. Modules serve as a
fundamental way to organize and reuse code in Python, promoting modularity and
maintainability in larger projects.
Here's a breakdown of key aspects of Python modules:
Content: A module can define functions, classes, variables, and even runnable code. It acts
as a container for related functionalities.
Organization: Modules help break down large programs into smaller, manageable, and
logically organized units.
Reusability: Code defined in a module can be easily imported and used in other Python
scripts or modules, avoiding code duplication.
Namespace Isolation: Each module has its own namespace, preventing naming conflicts
between different parts of a program.
Importing Modules:
You use the import keyword to bring the contents of a module into your current script or
module.
1. import math # Imports the entire 'math' module
print(math.sqrt(16))
2. from datetime import date # Imports only the 'date' class from 'datetime'
today = date.today()
print(today)
3. import os as system_ops # Imports 'os' module and gives it an alias
print(system_ops.getcwd())
Advantages of Using Modules
- Reusability – write once, use many times.
- Simplicity – program divided into logical parts.
- Maintainability – easier to fix/update code.
9
Python Programming
Types of Modules:
Built-in Modules:
These are modules that come pre-installed with Python, such as math, os, sys,
datetime, etc.
Example:-
import math
print(math.sqrt(25)) # 5.0
print(math.factorial(5)
User-defined Modules:
You can create your own modules by writing Python code and saving it in a .py file.
Example:-
# mymodule.py
def greet(name):
return f'Hello, {name}!'
# main.py
import mymodule
print(mymodule.greet('Sania'))
Third-party Modules:
These are modules developed by the community and can be installed using package
managers like pip (e.g., numpy, pandas, matplotlib).
Example:-
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr * 2) # [2 4 6 8]
In essence, modules are the building blocks for creating structured, reusable, and
maintainable Python applications.
10
Python Programming
Packages:
What are Packages in Python?
A python package creates a hierarchical directory structure with numerous modules and
sub-packages to give an application development environment. They are simply a collection
of modules and sub-packages.
Importance of Python Packages:
When working on a large or complex project, we frequently wind up with multiple modules.
Using, maintaining, and organising so many modules is challenging.
Fortunately, Python delivers us a simple solution in the form of packages. Using packages,
we can easily group, organise, and use multiple modules.
Packages also allow us to access all functions from all modules in a package with just one
import statement.
Structure of Python Packages
11
Python Programming
A simple Python package contains multiple modules and an __init__.py file. In addition to
these, a package can also contain various other sub-packages. To understand this better, the
following image illustrates the structure of Python packages.
Python Packages vs Directories
Although a package is also a directory, the main distinction between these two is that the
package contains __init__.py file and the directory doesn’t. The __init__.py file makes an
ordinary directory into a Python package. The following image clearly illustrates the
difference between the structure of a directory and the structure of a package.
Creating a Package in Python:
Let us create a package with two different modules. Creating a directory is the first step in
creating a package.
Let’s create a directory school.
The following step is to add two Python modules to the directory.
Let’s create two Python modules named students and teachers with the following codes.
Example on creating a package
Code in file students.py
def getStudents():
print("There are total 2500 students")
Code in file teachers.py
12
Python Programming
def getTeachers():
print("There are total 50 teachers")
__init__.py file:
One of the most important steps in creating a package is to create a __init__.py file. This file
is what distinguishes a package and a normal directory. It initializes the package when we
import it. This file is also called a Package Constructor.
Using a Package in Python:
To use a package, We simply need to import the package into our python file by using the
from and import keywords and dot operators.
Example on using packages
Code in file main.py
from school.students import getStudents
from school.teachers import getTeachers
getStudents()
getTeachers()
Output
There are total 2500 students
There are total 50 teachers
Python Package aliasing:
We can use the as keyword to assign a new name to the imported package for better
convenience.
Example on aliasing in Python
Code in file main.py
import school.students as s
import school.teachers as t
s.getStudents()
t.getTeachers()
13
Python Programming
Output
There are total 2500 students
There are total 50 teachers
Creating a Sub-Package in Python
Python packages often contain multiple sub-packages. Creating a sub-package is similar to
creating a normal package. We need to create a __init__.py file and one or more python
modules. Let’s create a sub-package named kindergarten to our previously created package
called school.
The sub-package contains the two modules kids and games with the following code.
Example on creating a sub-package
Code in file kids.py
def getKids():
print("There are total 30 kids")
Code in file games.py
def ChessTime():
print("Kids are playing Chess")
Similar to a package, a sub-package also needs a __init__.py file.
Illustrative programs: Word count
Program to count words in a file or string
# Method 1: Word count from a string
text = "Python is simple and powerful. Python is easy to learn."
words = text.split() # Split text into words
word_count = len(words)
print("Total number of words:", word_count)
14
Python Programming
# Method 2: Word count with frequency of each word
from collections import Counter
word_freq = Counter(words)
print("\nWord Frequency:")
for word, count in word_freq.items():
print(word, ":", count)
Output:
Total number of words: 9
Word Frequency:
Python : 2
is : 2
simple : 1
and : 1
powerful. : 1
easy : 1
to : 1
learn. : 1
Program to copy file and count characters, words, and lines
# Open source file in read mode
with open("source.txt", "r") as src:
# Open destination file in write mode
with open("destination.txt", "w") as dest:
char_count = 0
word_count = 0
line_count = 0
15
for line in src:
dest.write(line) # Copy line into destination
line_count += 1 # Count lines
char_count += len(line) # Count characters
word_count += len(line.split()) # Count words
print("File copied successfully!")
print("Total Lines:", line_count)
print("Total Words:", word_count)
print("Total Characters:", char_count)
Output:
File copied successfully!
Total Lines: 2
Total Words: 6
Total Characters: 32
Explanation:
1. source.txt → the original file.
2. destination.txt → the new file where contents will be copied.
3. with open() is used for safe file handling (it closes file automatically).
----THE END----
16