Module 4
File Handling: About files, Writing our first file, Reading a file line-by-line, Turning a
file into a list of lines, Reading the whole file at once
Modules & Packages: Importing the module, Three import statement variants,
Standard libraries (os, sys, math, random, datetime), Attributes and the dot Operator
Exception Handling: Definition, try, except, else, finally, Raising custom exceptions.
By
Prof Mahalaxmi Bellubbi
Dept CSE
File Handling
• File handling refers to the process of performing operations on a file,
such as creating, opening, reading, writing and closing it through a
programming interface. It involves managing the data flow between
the program and the file system on the storage device, ensuring that
data is handled safely and efficiently.
•Why do we need File Handling
• To store data permanently, even after the program ends.
• To access external files like .txt, .csv, .json, etc.
• To process large files efficiently without using much memory.
• To automate tasks like reading configs or saving outputs.
Opening a File
• To open a file, we can use open() function, which requires file-path and mode as arguments:
• Syntax:
file = open('[Link]', 'mode')
[Link]: name (or path) of the file to be opened.
mode: mode in which you want to open the file (read, write, append, etc.).
Note: If you don’t specify the mode, Python uses 'r' (read mode) by default.
Example:
f = open(“[Link]", "r")
print(f)
• Output:
<_io.TextIOWrapper name=‘[Link]' mode='r' encoding='UTF-8’>
NOTE:
_io.TextIOWrapper → Python's file object type
name=‘[Link]' → the file name
mode='r' → opened for reading
encoding='UTF-8' → default text encoding
• To print the content of the file:
f = open(“[Link]", "r")
print([Link]())
• Output:
• hi hello mahalaxmi
Closing a File
• The [Link]() method closes the file and releases the system resources. If the
file was opened in write or append mode, closing ensures that all changes are
properly saved.
file = open("[Link]", "r")
# Perform file operations
[Link]()
We will also see later how closing can be handled automatically using the with
statement and how to ensure files close properly using exception handling.
Checking File Properties
f = open(“[Link]", "r") Explanation:
print("Filename:", [Link]) [Link]: Returns the name of the file that was
print("Mode:", [Link]) opened (in this case, "[Link]").
print("Is Closed?", [Link]) [Link]: Tells us the mode in which the file
[Link]() was opened. Here, it’s 'r' which means read
print("Is Closed?", [Link]) mode.
[Link]: Returns a boolean value- False when
Output: file is currently open otherwise True.
Filename: [Link]
Mode: r
Is Closed? False
Is Closed? True
Reading a File
• Reading a file can be achieved by [Link]() which reads the entire content of
the file. After reading, it’s good practice to close the file to free up system
resources.
Example:
file = open(“[Link]", "r")
content = [Link]()
print(content)
[Link]()
Output:
hi hello mahalaxmi
f = open(“[Link]", "r")
for line in f:
print(line)
[Link]()
Read a file line by line in Python
• Python provides built-in functions for creating, writing, and reading files. Two types
of files can be handled in Python, normal text files and binary files (written in binary
language, 0s, and 1s). In this article, we are going to study reading line by line from a
file.
• Example:
with open('[Link]', 'r') as file:
for line in file:
print([Link]())
Output:
Hello, Python!
File handling is easy with Python.
Good morning to all
Wel come to pythons subject
>>>
Using Loop
• An iterable object is returned by open() function while opening a file. This final
way of reading a file line-by-line includes iterating over a file object in a loop. In
doing this we are taking advantage of a built-in Python function that allows us to
iterate over the file object implicitly using a for loop in combination with using the
iterable object.
L = ["Good morning\n", "for\n", "students\n"]
file1 = open(‘[Link]', 'w')
[Link](L)
[Link]() Output:
file1 = open(‘[Link]', 'r') Using for loop
Line1: Good morning
count = 0 Line2: for
print("Using for loop") Line3: students
for line in file1:
count += 1
print("Line{}: {}".format(count, [Link]()))
[Link]()
Writing a File
• In Python, writing to a file is done using the mode "w". This creates a
new file if it doesn’t exist, or overwrites the existing file if it does. The
write() method is used to add content. After writing, make sure to close
the file.
• Example: Writing to a file (overwrites if file exists)
with open(“[Link]", "w") as file:
[Link]("Hello, Python!\n")
[Link]("File handling is easy with Python.")
print("File written successfully")
Using with Statement
• Instead of manually opening and closing the file, you can use the with
statement, which automatically handles closing. This reduces the risk of file
corruption and resource leakage.
Example:
with open("[Link]", "r") as file:
content = [Link]()
print(content)
Output:
Hello, Python!
File handling is easy with Python.
Turning a file into a list of lines
• Turning a file into a list of lines is a common task: you take each line of the file and
make it an element of a Python list so you can index, slice, transform, or process
lines easily.
• When we read a text file, we may want each line to become one item in a
[Link] gives us simple ways to do this.
Using readlines() (most common and easiest)
• readlines() reads every line from the file and stores them in a list.
Example:
with open("[Link]", "r") as f:
lines = [Link]()
print(lines)
Output:
['Good morning\n', 'for\n', 'students\n']
Using list(f)
• This also converts each line into list items.
• Example:
with open("[Link]", "r") as f:
lines = list(f)
print(lines)
Output:
['Good morning\n', 'for\n', 'students\n']
Using splitlines() (to remove newline)
If you don’t want \n at the end of each line, use splitlines().
Example:
with open("[Link]", "r") as f:
lines = [Link]().splitlines()
print(lines)
• Output:
['Good morning', 'for', 'students']
Handling Exceptions When Closing a File
• It's important to handle exceptions to ensure that files are closed properly, even if an
error occurs during file operations. Here, the finally block ensures the file is closed
even if an error occurs.
• Example:
try:
file = open("[Link]", "r")
content = [Link]()
print(content)
finally:
[Link]()
Output:
Hello, Python!
File handling is easy with Python.
Append new data to an existing file
• # Program to append data to a file
with open("[Link]", "a") as f:
[Link]("\nThis line is added later.")
print("Data appended successfully!")
Output:
Data appended successfully!
Count number of words in a file
• # Program to count words in a file
with open("[Link]", "r") as f:
text = [Link]()
words = [Link]()
print("Total Words:", len(words))
Output:
Total Words: 5
Count the number of lines in a file
• # Program to count lines in a file
with open("[Link]", "r") as f:
lines = [Link]()
print("Number of Lines:", len(lines))
Output:
Number of Lines: 3
Copy contents from one file to another
# Program to copy one file to another
with open("[Link]", "r") as f1:
data = [Link]()
with open("[Link]", "w") as f2:
[Link](data)
print("File copied successfully!")
Output:
File copied successfully!
Display only the first N lines of a file
# Program to display first 3 lines of a file
Input [Link]
with open("[Link]", "r") as f: Alice
for i in range(3): Bob
Charlie
line = [Link]() David
if not line:
break Output:
Alice
print(line, end="") Bob
Charlie
Write a list of items into a file
# Program to write a list into a file
fruits = ["Apple", "Banana", "Mango", "Orange"]
with open("[Link]", "w") as f:
for fruit in fruits:
[Link](fruit + "\n")
print("List written to file.")
Output:
List written to file.
Program to count vowels in a file
# Count vowels in a file
Input:
vowels = "aeiouAEIOU" Alice
Bob
count = 0
Output:
Total vowels: 4
with open("[Link]", "r") as f:
for ch in [Link]():
if ch in vowels:
count += 1
print("Total vowels:", count)
Program to write student details into a file
• # Write student details into a file
Output:
with open("[Link]", "w") as f: Enter name: Ravi
Enter age: 20
for i in range(3): Enter name: Anu
name = input("Enter name: ") Enter age: 19
Enter name: Kiran
age = input("Enter age: ") Enter age: 21
Student details saved!
[Link](f"{name} - {age}\n")
print("Student details saved!")
Program to count uppercase and lowercase letters
# Count uppercase and lowercase characters
upper = lower = 0
Input:
Alice
with open("[Link]", "r") as f: Bob
text = [Link]()
Output:Uppercase letters: 2
Lowercase letters: 6
for ch in text:
if [Link]():
upper += 1
elif [Link]():
lower += 1
print("Uppercase letters:", upper)
print("Lowercase letters:", lower)
Program to search for a word in a file
# Search for a word in a file
Input:
word = input("Enter word to search: ")
found = False Alice
Bob
Charlie
with open("[Link]", "r") as f: Output:
for line in f: Enter word to search: Bob
Word found!
if word in line:
found = True
break
if found:
print("Word found!")
else:
print("Word not found.")
Modules & Packages
• In Python, modules are single files containing code, while packages are
directories that organize related modules into a hierarchical namespace. Both
are fundamental to modular programming, promoting code reusability,
organization, and maintainability.
Modules
A module is a single Python file with a .py extension that can define
functions, classes, and variables
You can think of it as a code library.
•Creation: Simply write Python code and save it in a file with a .py extension
(e.g., [Link]).
•Usage: Modules are accessed using the import statement.
•import mymodule
•from mymodule import specific_function
•Examples: Python's standard library includes many built-in modules
like math, os, and datetime.
Packages
A package is a directory that organizes related modules and
sub-packages together, providing a way to structure larger projects.
•Structure: A package is essentially a folder. In Python versions before
3.3, it was required to contain a special file named __init__.py to be
recognized as a package. While no
•longer strictly required for simple namespace packages, it's still
commonly used for initialization code or to define what names are
exported when using from package import *.
•Usage: Modules within a package are accessed using dot notation.
•import package_name.module_name
•from package_name.module_name import function_name
•Examples: Popular third-party libraries like NumPy, Pandas,
and Django are distributed as packages.
Import module in Python
• In Python, modules help organize code into reusable files. They allow you to
import and use functions, classes and variables from other scripts. The import
statement is the most common way to bring external functionality into your
Python program.
• Python modules are of two types:
1. built-in (come with Python) module and
2. external modules like pandas and numpy.
1. Importing built-in Module
• Built-in modules can be directly imported using "import" keyword without
any installation. This allows access to all the functions and variables
defined in the module.
Example:
import math
pie = [Link]
print("Value of pi:", pie)
Output:
Value of pi: 3.141592653589793
Importing External Modules
To use external modules, we need to install them first, we can easily install any external module
using pip command in the terminal, for example:
pip install module_name
Make sure to replace "module_name" with the name of the module we want to install,
example: pandas, numpy, etc.
After installation, we can import the module like a regular built-in module using "import
statement".
Example:
import pandas
# Create a simple DataFrame Output:
data = { Name Age
"Name": ["Elon", "Trevor", "Swastik"], 0 Elon 25
1 Trevor 30
"Age": [25, 30, 35] 2 Swastik 35
}
df = [Link](data)
print(df)
Three Import Statement Variants in Python
• Python uses modules to organize code. To use the functions,
variables, or classes defined in a module, we must import that
module. Python provides three main import statement variants, each
serving a different purpose.
1. import module_name
•This statement imports the entire module.
•All functions, variables, and classes inside the module
become available.
•To access any member, we must use the dot operator (.)
•Syntax:
•import module_name
•Example:
•import math
•print([Link](25))
•print([Link])
2. import module_name as alias
This is similar to the first variant, but the module is given a short or
alternate name.
The alias is used instead of the full module name.
Commonly used when module names are long.
Syntax:
import module_name as alias
Example:
import math as m
print([Link](5))
print([Link](16))
3. from module_name import name
•Imports specific members (functions, variables, or classes)
from a module.
•No need to use the module name or dot operator.
•Only selected items are loaded into memory.
•Syntax:
from module_name import name
Example:
from math import sqrt, pi
print(sqrt(9))
print(pi)
Special Case: Importing All Members
Example:
from math import *
print(sin(0))
• It imports everything
• Can overwrite existing names
• Makes debugging difficult
Standard libraries (os, sys, math, random, datetime)
• os: Provides a portable way of interacting with the operating system. It is used for tasks
like manipulating file paths, managing directories, and accessing environment variables.
• Common functions: [Link]() (get current working directory), [Link]() (list files in a
directory), [Link]() (create a directory).
Example:
import os
Output:
print("Current Working Directory:") Current Working Directory:
print([Link]()) C:\Users\Student
• sys: Provides access to system-specific parameters and functions, primarily for interacting
with the Python interpreter itself.
• Common uses: Accessing command-line arguments ([Link]), controlling the interpreter's exit
behavior ([Link]()), and interacting with standard input/output streams.
• Example:
import sys Output:
Python Version:
3.11.4 (main, Jun 7 2023, 10:30:12)
print("Python Version:") [MSC v.1934 64 bit (AMD64)]
print([Link])
• math: Supplies mathematical functions and constants beyond basic arithmetic
operators.
• Example:
import math Output:
Square Root of 16: 4.0
Factorial of 5: 120
print("Square Root of 16:", [Link](16)) Value of Pi: 3.141592653589793
print("Factorial of 5:", [Link](5))
print("Value of Pi:", [Link])
• random: Generates pseudo-random numbers and provides functions for random
selections and simulations.
Example:
import random
Output:
Random Number between
print("Random Number between 1 and 10:") 1 and 10:
print([Link](1, 10)) 7
• datetime: Contains classes for manipulating dates and times, including date
arithmetic and formatting.
Example:
from datetime import datetime
now = [Link]()
print("Current Date and Time:") Output:
Current Date and Time:
print(now) 2025-12-16 12:05:30.123456
Exception Handling
• Exception handling in Python provides a structured approach to manage
runtime errors that occur during program execution. It helps the program
recognize unexpected events, handle them gracefully, and maintain normal
execution instead of crashing.
• Exception Handling is a mechanism in Python used to detect and handle
runtime errors (exceptions) so that the normal flow of a program is not
interrupted.
Difference Between Errors and Exceptions
Errors and exceptions are both issues in a program, but they differ in severity
and handling. Let's see how:
• Error: Serious problems in the program logic that cannot be handled.
Examples include syntax errors or memory errors.
• Exception: Less severe problems that occur at runtime and can be managed
using exception handling (e.g., invalid input, missing files).
• Python provides four main keywords for handling exceptions: try, except,
else and finally each plays a unique role. Let's see syntax:
• Syntax
• try:
# Code
except SomeException:
# Code
else:
# Code
finally:
# Code
• try: Runs the risky code that might cause an error.
• except: Catches and handles the error if one occurs.
• else: Executes only if no exception occurs in try.
• finally: Runs regardless of what happens useful for cleanup tasks like closing
files.
Try Except in Python
• Try and Except statement is used to handle these errors within our code in
Python. The try block is used to check some code for errors i.e the code
inside the try block will execute when there is no error in the program.
Whereas the code inside the except block will execute whenever the
program encounters some error in the preceding try block.
• syntax:
try:
# Some Code
except:
# Executed if error in the
# try block
Why do we need try-except
• Prevents crashes caused by runtime errors.
• Handles specific exceptions like division by zero, file not found, etc.
• Improves code reliability and error tolerance.
• Allows custom error messages and fallback logic.
• Essential for robust, debuggable applications.
Some of the common Exception Errors are :
• IOError: if the file can't be opened
• KeyboardInterrupt: when an unrequired key is pressed by the user
• ValueError: when the built-in function receives a wrong argument
• EOFError: if End-Of-File is hit without reading any data
• ImportError: if it is unable to find the module
/* Write a python program to perform divide by 0 exception handling using try
and except*/
try:
n=0
res = 100 / n
except ZeroDivisionError:
print("You can't divide by zero!")
Output:
except ValueError: You can't divide by zero!
print("Enter a valid number!") Execution complete.
else:
print("Result is", res)
finally:
print("Execution complete.")
try:
a = int(input("Enter a number: "))
b = int(input("Enter another number: ")) Output:
Enter a number: 10
result = a / b Enter another number: 2
Result: 5.0
except ZeroDivisionError:
print("Division by zero error")
else:
print("Result:", result)
Else Clause
• In Python, you can also use the else clause on the try-except block which must
be present after all the except clauses. The code enters the else block only if the
try clause does not raise an exception.
• Syntax:
• try:
# Some Code
except:
# Executed if error in the
# try block
else:
# execute if no exception
Finally Keyword in Python
• Python provides a keyword finally, which is always executed after the try and
except blocks. The final block always executes after the normal termination
of the try block or after the try block terminates due to some exceptions.
• The finally block always executes, whether an exception occurs or not.
Used for cleanup actions (closing files, releasing resources).
• Syntax:
try:
# Some Code
except:
# Executed if error in the
# try block
else:
# execute if no exception
finally:
# Some code .....(always executed)
# Python program to demonstrate finally
# No exception Exception raised in try block
try:
k = 5//0 # raises divide by zero exception.
Output:
print(k) Can't divide by zero
This is always executed
# handles zerodivision exception
except ZeroDivisionError:
print("Can't divide by zero")
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
Keyword Purpose
Code that may cause an
try
exception
except Handles the exception
Executes if no exception
else
occurs
finally Executes always
Raises custom or built-in
raise
exception
Multiple except Statements in Python
• In Python, multiple except statements are used when a try block can raise different
types of exceptions, and each exception needs to be handled in a different way.
• This helps the program respond appropriately to each specific error instead of using
a single general handler.
• Syntax:
try:
# code that may raise exceptions
except ExceptionType1:
# handling code
except ExceptionType2:
# handling code
else:
# executes if no exception occurs
finally:
# executes always
try:
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))
Output 1:
result = a / b Enter a number: 10
print("Result:", result) Enter another number: 0
Error: Division by zero is not allowed
Output 2:
except ZeroDivisionError: Enter a number: ten
Error: Please enter valid integers
print("Error: Division by zero is not allowed") Output 3:
Enter a number: 10
Enter another number: 2
except ValueError: Result: 5.0
print("Error: Please enter valid integers")
except Exception:
print("Error: Some unexpected error occurred")
Thank You