Python - Unit IV
Python - Unit IV
Files and exception: Text Files, Reading and Writing files, Format operator; Errors and Exceptions,
Handling Exceptions, Multiple Except blocks, Modules, Packages; Illustrative programs: word count,
copy file, Creating user defined Exceptions.
What is a File?
• A file is a collection of data stored on a secondary storage device like a hard disk.
• Initially, data was entered using the input() function, which is fine for small data.
• But when data becomes large, it becomes tedious and inefficient to process it manually each
time.
• Better solution: Combine data into a file and use a Python program to read/write from it
when needed.
1
Basic Steps in File I/O:
1. Open the file (for reading, writing, or both)
2. Read from or write to the file
3. Close the file (to free up system resources)
FILE PATH
• Files are stored on a storage medium like a hard disk.
• The storage is organized so that files can be easily retrieved whenever required.
• Most modern file systems store files in a tree (or hierarchical) structure.
• This hierarchical system allows files to be organized in folders and subfolders, making it easier
to manage and locate them.
Example:
File: BTech_CS.docx
Location:
C:\Students\Under Graduate\BTech_CS.docx
Explanation:
• C: – Root drive
• Students – Folder
• Under Graduate – Subfolder
• BTech_CS.docx – File
TYPES OF FILE
2
• Text files process characters, not raw data like binary files.
• They are human-readable.
• A line can have up to 255 characters.
• Each line ends with newline characters.
• The file ends with a special character called EOF (End Of File).
• After the last line of the file, the computer adds a hidden marker called EOF.
• EOF = End Of File
Apple\n
• It tells the computer:
Banana\n
👉 “Stop reading! The file is over.” Orange\n
EOF
2. Binary Files
• A binary file stores any type of data in binary form (e.g., documents, images, PDFs, programs).
• It is different from a text file in that it handles bytes rather than characters.
• No special processing is needed; each byte is transferred as-is to/from disk.
• Python allows reading/writing binary files in any format without restrictions.
• Binary files can be accessed sequentially or randomly depending on the application's needs.
• When updating binary data (e.g., student records), the programmer:
o Locates the required record,
o Reads it into memory,
o Modifies it,
o Writes it back to the appropriate file location.
✓ Binary files store data in internal representation (e.g., integers stored as 2-byte values).
✓ Binary files, like text files, end with an EOF (End of File) marker.
✓ In a text file, an integer like 123 is stored as 3 characters: '1', '2', and '3', requiring 3 bytes.
✓ In a binary file, the same integer 123 is stored in 2 bytes in binary form.
✓ Binary files are more efficient in terms of storage and processing since they:
o Take less space,
o Avoid conversion between internal and external data representations.
✓
3
FILE I/O OPERATIONS
Python provides many in-built functions and methods to manipulate files, which primarily operate on
file objects.
• Purpose:
Before reading from or writing to a file, you must open it using Python’s built-in open()
function. This function creates a file object used to invoke file-related methods.
Parameters:
• file_name: A string representing the name of the file you want to access.
• access_mode: (Optional) A string that indicates the mode of file access, e.g., read (r), write
(w), append (a), etc.
• If access_mode is not specified, the default mode is read (r).
Return Value:
• The open() function returns a file object, which allows operations such as reading, writing, or
appending.
• It behaves like a file handle.
Example:
file = open("File1.txt", "rb")
print(file)
Output: <open file 'File1.txt', mode 'rb' at 0x02A850D0>
rb - Read Binary Mode – It opens the file for reading in binary format (not as text).
4
a Append Opens for appending. Pointer at end You can only add content to the end of
the file. Creates file if not exists. Keeps existing content. Write-only mode.
ab Append (binary) Same as a, but in binary mode. Appends data at end.
a+ Append & Read Opens for reading and appending. Pointer at end, writing always happens at
the end. Creates file if not exists.
ab+ Append & Read Same as a+, but in binary mode. Pointer at end. Creates file if not exists.
(binary)
Once a file is opened using the open() function, it returns a file object. This object provides various
attributes to get information about the file.
Attribute Description
fileObj.closed Returns True if the file is closed, False if it's still open.
fileObj.mode Returns the access mode used to open the file (e.g., "r", "wb+").
fileObj.name Returns the name of the file.
Example:
file = open("example.txt", "r")
print(file.closed) # False
print(file.mode) # 'r'
print(file.name) # 'example.txt'
file.close()
print(file.closed) # True
Purpose:
The close() method is used to close a file object in Python. Once closed, you cannot read from or
write to the file.
Functionality:
• Flushes any unwritten data to the file (ensures all buffered output is written to disk).
• Frees system resources like file descriptors, file locks, etc., that are tied to the file.
5
Syntax: fileObj.close()
Important Notes:
• Python may automatically close a file when the reference is reassigned, but it's good practice
to always close files explicitly using close().
• Not closing files can lead to:
o Memory wastage
o Hitting the limit of open files, which may crash the program
o Data loss or corruption
• After calling close(), any operation on the file object will raise an error.
• Purpose: read() and write() functions are used to read from and write to files.
▪ write() Method
✓ Used to write a string to an already opened file.
✓ Can include:
o Numbers
o Special characters
o Symbols
Note: write() does not add a newline (\n) at the end automatically.
6
Syntax: fileObj.write(string)
The string passed as an argument is written directly into the opened file.
• After storing data in a file, you can open it again to append more data.
• This is done using:
o 'a' mode for text files
o 'ab' mode for binary files
• Appending allows adding content without overwriting the existing data in the file.
• If you open a file in 'w' (write) or 'wb' (write binary) mode and write data, existing contents will be
overwritten.
7
iii) read() and readline() Methods
➢ read() Method:
Syntax: fileObj.read([count])
• Parameters:
o count (optional): Specifies the number of bytes to read from the file.
o If count is not provided or has a negative value, the entire file content is read.
• Behavior:
o Begins reading from the start of the file.
o If count is provided, reads up to count bytes.
o If not, reads until the end of the file.
8
➢ readline() Method
Notes:
• A blank line in a file is represented by \n.
• When a blank line is encountered, the method returns a string with only the newline
character ('\n').
• read() method also includes newline characters (\n) in its output.
➢ readlines() Method
Syntax: file.readlines()
• Returns: A list, where each item is a line from the file, including \n.
9
➢ Using list() to Read File Contents
✓ The list() function can be used to display the entire contents of a file.
✓ Pass the file object to the list() function:
file = open("example.txt", "r")
content = list(file)
print(content)
➢ Splitting Words
• Python allows you to read line(s) from a file and split the line into words.
• The line is treated as a string, and you can use the .split() method to divide it based on a
separator character.
• By default, .split() uses space (" ") as the delimiter.
• You can specify any character as the delimiter:
line = "apple,banana,cherry"
words = line.split(",")
print(words) # ['apple', 'banana', 'cherry']
✓ Often used after reading a line from a file to process individual words or tokens.
8. Write a program that will prompt the user for a string and a file name, and then print all lines in
the file that contain the string. Also interpret the obtained result.
Program:
search_string = input("Enter the string to search for: ")
filename = input("Enter the file name: ")
try:
file = open(filename, 'r')
for line in file:
if search_string in line:
print(line.strip())
file.close()
10
except:
print("Error: File not found or could not be opened.")
Suppose you have a file called example.txt with the following content:
Welcome to Python programming.
This course is about learning coding.
Python is very easy to learn.
We are practicing file handling today.
Good luck with your learning!
10. Illustrate a program to find the one’s complement of binary number using file.
Program
filename = input("Enter the file name: ")# Step 1: Ask the user to enter the file
name
try:
file = open(filename, 'r') # Step 2: Try to open the file in 'read'
mode
binary = file.read().strip() # Step 3: Read the content and remove
any extra spaces or newlines
file.close() # Step 4: Close the file after reading
print("Original binary number:", binary)# Step 9: Print the original binary number
print("One's complement:", ones_complement) # Step 10: Print the one's complement
except: # Step 11: If there is any problem (like file not found), show this message
print("Error: File not found or invalid content.")
11
When you run the program:
13. Write a program to count the total number of uppercase characters in a file.
Program
def count_uppercase_characters(filename):
count = 0
try:
with open(filename, 'r') as file:
for line in file:
for char in line:
if char.isupper():
count += 1
print(f"Total number of uppercase characters: {count}")
except FileNotFoundError:
print(f"The file '{filename}' was not found.")
# Example usage
filename = input("Enter the filename: ")
count_uppercase_characters(filename)
Explanation
• It asks the user to enter the filename.
• Then it calls the function with the filename.
• A function named count_uppercase_characters is created.
• It takes one input called filename (the name of the file you want to check).
• A variable count is set to 0.
• It will be used to count how many uppercase letters are found.
• try means you are trying to open the file safely.
• open(filename, 'r') opens the file in read mode ('r').
• with ensures the file is automatically closed after reading.
• for line in file: This loop reads the file one line at a time.
Output
• Open sample.txt
• Check each character in every line
• Count only the uppercase letters: H, W, T, T, F, I, P, I, F
12
• So total uppercase characters = 9
If the filename you type does not exist, you will see:
16. Explain with an example to copy the contents of one file to another.
Program
def copy_file(source_file, destination_file):
try:
with open(source_file, 'r') as src:
with open(destination_file, 'w') as dest:
for line in src:
dest.write(line)
print(f"Contents copied from '{source_file}' to '{destination_file}'
successfully.")
except FileNotFoundError:
print(f"The file '{source_file}' was not found.")
# Example usage
source = input("Enter the source filename: ")
destination = input("Enter the destination filename: ")
copy_file(source, destination)
Output
Suppose you have a file called source.txt with content:
Hello Students,
Welcome to Python Programming.
The program will create a file destination.txt with the same content:
Hello Students,
Welcome to Python Programming.
Contents copied from 'source.txt' to 'destination.txt' successfully.
13
18. Write a program that reads the contents of the file text.txt and counts the number of alphabets,
blank spaces, lowercase letters and uppercase letters, the number of words starting with a vowel,
and the number of occurrences of each word in the file.
import re
from collections import Counter
def is_vowel(word):
return word[0].lower() in 'aeiou'
# Initialize counters
alphabet_count = sum(c.isalpha() for c in text)
blank_space_count = text.count(' ')
lowercase_count = sum(c.islower() for c in text)
uppercase_count = sum(c.isupper() for c in text)
# Display results
print(f"Number of alphabets: {alphabet_count}")
print(f"Number of blank spaces: {blank_space_count}")
print(f"Number of lowercase letters: {lowercase_count}")
print(f"Number of uppercase letters: {uppercase_count}")
print(f"Number of words starting with a vowel: {vowel_start_count}")
print("Occurrences of each word:")
for word, count in word_occurrences.items():
print(f"{word}: {count}")
Output
Number of alphabets: 61
Number of blank spaces: 14
Number of lowercase letters: 47
Number of uppercase letters: 3
Number of words starting with a vowel: 6
Occurrences of each word:
apple: 1
is: 3
a: 3
14
fruit: 2
orange: 1
also: 1
banana: 1
not: 1
vegetable: 1
Explanation
12. Explain the terminology of raising an exception concept with sample program.
ERROR
An error is an abnormal condition or defect that occurs during program execution, making it
impossible for the program to continue running normally.
Types
i) Syntax Errors: Arise from poor understanding of the language. Can be detected through debugging
and testing.
✓ Syntax errors occur when we violate the rules of Python.
✓ These are the most common errors faced by beginners.
Example: i = 0
if i == 0 print(i) Correct Code: i=0
if i == 0:
You must add a colon (:) after the if condition. print(i)
15
ii) Logic Errors: Logic errors occur when the program runs without crashing but produces incorrect
results. They happen due to wrong algorithms or wrong logical flow.
Examples:
1. Wrong logic in division:
a = 10
b = 5
print("Result:", a + b) # Wrong logic, should be division
o Expected: 2
o Actual Output: 15
2. Accessing wrong index in a list:
items = [1, 2, 3]
print(items[5]) # Index out of bounds
Important:
Logic errors can sometimes lead to runtime errors (called exceptions) like:
• ZeroDivisionError
• IndexError (list index out of range)
EXCEPTION
An exception is an event that occurs during the execution of a program that disrupts the normal flow
of instructions but can usually be handled using proper code (like try-except blocks).
✓ Even if a program is syntactically correct, it can still cause errors while running. Such errors
during execution are called exceptions.
✓ Represent anomalies or unusual conditions like:
o Divide by zero
o Array index out of bounds
o Running out of memory or disk space
o Overflow and underflow
Types
i) Synchronous Exceptions:
o Occur due to program's actions (e.g., divide by zero, array out of bounds).
o Can be controlled by the program.
Example
a = 10
b = 0
print(a / b)
16
ii) Asynchronous Exceptions:
o Caused by external events (e.g., keyboard interrupt, hardware malfunction, disk
failure).
o Beyond the control of the program.
HANDLING EXCEPTIONS
• Definition:
We can handle errors in a program using the try block and except block.
• Purpose:
o Code that might cause an error is written inside the try block.
o Code that handles the error is written inside the except block.
Syntax:
try:
statements
except ExceptionName:
statements
1. Step 1:
The code inside the try block is executed first.
2. Step 2a:
If no error occurs → the except block is skipped.
3. Step 2b:
If an error occurs while running the try block:
o i. Remaining statements inside try are skipped.
o ii. If the error matches the ExceptionName, the except block is executed.
o iii. If no matching except block is found → the program stops with an error
message (called Unhandled Exception).
17
RAISING AN EXCEPTION
• Raising an Exception means manually creating an exception in your program using the raise
keyword.
• It is used when you want to trigger an error intentionally under certain conditions.
• You can raise built-in exceptions (like ValueError, ZeroDivisionError) or create and
raise your own custom exceptions.
• ExceptionType is the type of exception you want to raise (e.g., ValueError, TypeError).
• "Error message" is a description that will help users understand what went wrong.
Example
age = int(input("Enter your age: ")) Output
Enter your age: -5
try:
if age < 0: An error occurred: Age cannot
raise ValueError("Age cannot be negative!") be negative!
else:
print(f"Your age is {age}.")
except ValueError as e:
print("An error occurred:", e)
• raise immediately stops normal flow and moves control to the nearest except block.
• It is useful for validating inputs, enforcing rules, or handling unexpected cases manually.
4. (i) Describe the use of try block and except block in python with syntax. (ii) Describe with an
example exception with arguments in python.
✓ Python allows you to have multiple except blocks for a single try block. A single try statement
can have multiple except statements to catch different types of exceptions.
✓ The except block that matches the exception generated will get executed.
✓ A try block can be associated with more than one except block to handle different exceptions.
✓ Only one handler (the first matching one) will be executed even if multiple handlers are
present.
✓ Exception handlers handle exceptions that occur only in their corresponding try block.
✓ The syntax for specifying multiple except blocks for a single try block is:
18
Important Points:
• Only one matching except block executes.
• After exception handling, normal flow resumes.
• Multiple except blocks make the program robust and able to handle different types of errors
separately.
Example :
KeyboardInterrupt:
• If the user interrupts the program (for example, by pressing Ctrl + C), the
KeyboardInterrupt exception is raised.
ValueError:
• If the user enters a non-numeric value (like "abc"), the ValueError exception is raised.
• Here, "abc" is not a number, so a ValueError occurs and its handler runs.
• After handling the exception, the program continues and prints "Bye".
▪ An except clause can handle multiple exceptions by listing them inside a parenthesized tuple
(Exception1, Exception2, Exception3, ...).
▪ When any one of the specified exceptions occurs, the same except block will be executed.
▪ This is useful to group related exceptions together and handle them with common code.
Syntax:
try:
# Code that may cause multiple types of exceptions
except (ExceptionType1, ExceptionType2, ExceptionType3):
# Common handling code for all listed exceptions
19
The except block mentions three exceptions together inside parentheses:
• KeyboardInterrupt → If the user interrupts the program (like pressing Ctrl + C).
• ValueError → If the user enters non-numeric data (like "abc").
• TypeError → If there’s a type mismatch.
Important rule:
→No code should be written between the try block and the except block(s).
→After try, you must immediately list all except blocks.
3. (i) Discover a program to catch a divide by zero exception. Add a finally block too. (ii) Write a
function to print the hash of any given file in Python.
MODULES
14. Explain the following: (i) Predefined Modules and (ii) User defined Modules
7. Explain python modules and packages.
Definition
• A module in Python is a file with a .py extension that contains definitions of functions and
variables.
• It enables reusability by allowing the use of functions and variables defined in one file within
other programs.
Purpose:
• Modules help to reuse one or more functions in your program, even if those functions are not
defined within the current file.
• They serve as an extension to functions by allowing the reuse of entire code blocks across
different programs.
Modules are pre-written pieces of code used to perform common tasks such as generating random
numbers, performing mathematical operations, and more.
✓ import is a keyword in Python used to bring in (load) a module into your program so you
can use its functions, classes, or variables.
Example
import math
print(math.sqrt(16)) # Output: 4.0
✓ This imports the math module and uses its sqrt() function to calculate the square root of
16.
PREDEFINED MODULES
✓ These are pre-installed modules that come with Python.You can use them directly by
importing.
20
Examples:
• math – for mathematical operations
• random – for generating random numbers
• datetime – for working with dates and times
• sys – for system-specific functions
i) from...import Statement
• Used to import specific items (functions/variables) from a module.
• This is useful when you don’t want the entire module, just certain parts.
Example :
from math import pi
print("PI =", pi) # Output: PI = 3.14159...
• Importing Multiple Items : To import more than one item (function or variable) from a
module by using a comma-separated list.
Syntax: from module_name import item1, item2
Example:
from math import pi, sqrt
radius = 4 Output:
area = pi * radius * radius
Area of circle: 50.26548245743669
root = sqrt(16)
Square root of 16: 4.0
print("Area of circle:", area)
print("Square root of 16:", root)
• Import All Items : imports all names (functions, variables, constants) from a module except
those whose names start with an underscore (_).
• Using as to Rename Items: The as keyword allows importing a module with an alias (a
different name). It is useful when the module name is long or confusing name.
• sys.exit() in Python
sys.exit([arg]) is used to terminate a Python program.
arg is optional:
o If arg is an integer:
▪ 0 means successful termination.
▪ Any non-zero value indicates an error or abnormal termination.
o If arg is not an integer (like a string or object), the exit code will be 1 (error).
o None is treated the same as passing 0.
Example:
# file: example.py
print("This runs always.")
if __name__ == "__main__":
print("This runs only when this file is the main module.")
Output:
This runs always.
This runs only when this file is the main module.
Output:
This runs always.
(The second print does not run because it’s not the main module.)
Identifiers include:
• Functions
• Variables
• Classes
• Other modules or objects
Example
x = 10 # Variable assignment
22
print_var(x) # Function call with x = 10
print(dir()) # Print the list of identifiers in the current scope
Output
10
['__builtins__', '__doc__', '__file__', '__name__', '__package__',
'print_var', 'x']
Explanation:
USER-DEFINED MODULES
• These are Python files created by the programmer to organize reusable code.
• You can import them into other programs.
Example:
Step 1: Create a module — my_module.py
# my_module.py
def display():
print("Hello")
print("Name of called module is:", __name__)
import my_module
my_module.display()
print(my_module.str)
Output of main.py:
Hello
Name of called module is: my_module
Welcome to the world of Python !!!
$ python my_module.py
# Nothing will happen unless you explicitly call display()
23
Then the output will be:
Hello
Name of called module is: __main__
PACKAGES
Structure:
my_package/
├── __init__.py
├── module1.py
└── module2.py
Purpose of __init__.py:
Example:
# module1.py
# Initialization message
print("mypackage initialized.")
24
# Optional: control what's imported when using "from mypackage import *"
__all__ = ['add', 'multiply']
# main.py
# Now we can directly import add and multiply from the package
from mypackage import add, multiply
result1 = add(10, 5)
result2 = multiply(4, 3)
15. Write a program that validates name and age as entered by the user to determine whether the
person can cast vote or not.
def is_valid_name(name):
# Check if name contains only alphabets and is not empty
return name.isalpha()
def is_valid_age(age_str):
# Check if age is a digit and greater than or equal to 18
if age_str.isdigit():
age = int(age_str)
return age >= 18
return False
# Validate inputs
if not is_valid_name(name):
print("Invalid name. Please enter alphabetic characters only.")
elif not age_str.isdigit():
print("Invalid age. Please enter a numeric value.")
else:
age = int(age_str)
if age >= 18:
print(f"{name}, you are eligible to vote.")
else:
print(f"{name}, you are not eligible to vote. Minimum age is 18.")
25