0% found this document useful (0 votes)
7 views20 pages

Python File Handling and Exception Handling

This document provides a comprehensive reference on Python file handling and exception handling, detailing methods for opening, reading, writing, and closing files, as well as various file modes. It also covers exception handling techniques, including try-except blocks, handling multiple exceptions, and raising custom exceptions. Practical examples demonstrate file processing and input validation, emphasizing best practices for robust programming.

Uploaded by

S SA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views20 pages

Python File Handling and Exception Handling

This document provides a comprehensive reference on Python file handling and exception handling, detailing methods for opening, reading, writing, and closing files, as well as various file modes. It also covers exception handling techniques, including try-except blocks, handling multiple exceptions, and raising custom exceptions. Practical examples demonstrate file processing and input validation, emphasizing best practices for robust programming.

Uploaded by

S SA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Python File Handling and Exception Handling Reference

By Engr Aamir Jamil

File Handling

Opening and Closing Files

python

# Method 1: Manual open/close (not recommended)


file = open("example.txt", "r")
content = file.read()
file.close()

# Method 2: Using 'with' statement (recommended)


with open("example.txt", "r") as file:
content = file.read()
# File automatically closed after 'with' block

File Opening Modes

python
# Reading modes
"r" # Read text file (default)
"rb" # Read binary file

# Writing modes
"w" # Write text file (overwrites existing)
"wb" # Write binary file
"a" # Append to text file
"ab" # Append to binary file

# Read and write


"r+" # Read and write

Reading Files

python
# Read entire file
with open("data.txt", "r") as file:
content = file.read()
print(content)

# Read line by line (memory efficient)


with open("data.txt", "r") as file:
for line in file:
print(line.strip()) # Remove newline characters

# Read all lines into a list


with open("data.txt", "r") as file:
lines = file.readlines()
print(lines)

# Read one line at a time


with open("data.txt", "r") as file:
first_line = file.readline()
second_line = file.readline()

Writing Files

python
# Write to file (overwrites existing content)
with open("output.txt", "w") as file:
file.write("Hello World!")
file.write("\nSecond line")

# Write multiple lines


lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("output.txt", "w") as file:
file.writelines(lines)

# Append to file
with open("log.txt", "a") as file:
file.write("\nNew log entry")

# Write using print function


with open("output.txt", "w") as file:
print("Hello", file=file)
print("World", file=file)

Basic File Operations Examples

python
# Copy file content
with open("source.txt", "r") as source:
with open("destination.txt", "w") as dest:
content = source.read()
dest.write(content)

# Count lines in file


with open("data.txt", "r") as file:
line_count = sum(1 for line in file)
print(f"File has {line_count} lines")

# Read and process CSV-like data


with open("students.csv", "r") as file:
for line in file:
data = line.strip().split(",")
name, age, grade = data
print(f"Student: {name}, Age: {age}, Grade: {grade}")

Exception Handling

Basic Try-Except

python
# Handle specific exception
try:
number = int(input("Enter a number: "))
result = 10 / number
print(f"Result: {result}")
except ValueError:
print("Please enter a valid number!")
except ZeroDivisionError:
print("Cannot divide by zero!")

Multiple Exceptions

python

# Handle multiple exception types


try:
age = int(input("Enter age: "))
result = 100 / age
print(f"Result: {result}")
except (ValueError, TypeError):
print("Invalid input type!")
except ZeroDivisionError:
print("Age cannot be zero!")
except Exception as e:
print(f"Unexpected error: {e}")

Try-Except-Else-Finally

python
try:
file = open("data.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found!")
content = None
else:
print("File read successfully!") # Runs if no exception
finally:
print("Cleanup completed") # Always runs
if 'file' in locals():
file.close()

File Handling with Exception Handling

python
# Reading file safely
def read_file_safe(filename):
try:
with open(filename, "r") as file:
return file.read()
except FileNotFoundError:
print(f"Error: '{filename}' not found")
return None
except PermissionError:
print(f"Error: Permission denied for '{filename}'")
return None

# Writing file safely


def write_file_safe(filename, data):
try:
with open(filename, "w") as file:
file.write(data)
print(f"Data written to '{filename}' successfully")
return True
except PermissionError:
print(f"Error: Cannot write to '{filename}'")
return False
except Exception as e:
print(f"Error writing file: {e}")
return False

# Usage
content = read_file_safe("example.txt")
if content:
processed_content = content.upper()
write_file_safe("output.txt", processed_content)
Common Exception Types

python
# ValueError - Invalid value
try:
number = int("abc")
except ValueError:
print("Cannot convert 'abc' to integer")

# TypeError - Wrong type


try:
result = "hello" + 5
except TypeError:
print("Cannot add string and integer")

# IndexError - Invalid index


try:
my_list = [1, 2, 3]
print(my_list[10])
except IndexError:
print("Index out of range")

# KeyError - Invalid dictionary key


try:
my_dict = {"name": "Aamir"}
print(my_dict["age"])
except KeyError:
print("Key 'age' not found in dictionary")

# FileNotFoundError - File doesn't exist


try:
with open("nonexistent.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("File not found")

Raising Custom Exceptions

python

# Raise exceptions manually


def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
if age > 150:
raise ValueError("Age too high")
return True

def divide_numbers(a, b):


if b == 0:
raise ZeroDivisionError("Division by zero not allowed")
return a / b

# Using custom validation


try:
age = int(input("Enter age: "))
validate_age(age)
print(f"Valid age: {age}")
except ValueError as e:
print(f"Invalid age: {e}")
Practical Examples

Simple File Processing

python
# Read numbers from file and calculate statistics
def process_numbers_file(filename):
try:
with open(filename, "r") as file:
numbers = []
for line_num, line in enumerate(file, 1):
try:
number = float(line.strip())
numbers.append(number)
except ValueError:
print(f"Warning: Invalid number at line {line_num}: '{line.strip()}'")

if numbers:
total = sum(numbers)
average = total / len(numbers)
return {
"count": len(numbers),
"sum": total,
"average": average,
"min": min(numbers),
"max": max(numbers)
}
else:
return None

except FileNotFoundError:
print(f"File '{filename}' not found")
return None

# Usage
stats = process_numbers_file("numbers.txt")
if stats:
print(f"Count: {stats['count']}")
print(f"Average: {stats['average']:.2f}")

Simple Student Records System

python
def add_student_record(filename, name, age, grade):
"""Add student record to file"""
try:
with open(filename, "a") as file:
file.write(f"{name},{age},{grade}\n")
print(f"Added record for {name}")
return True
except Exception as e:
print(f"Error adding record: {e}")
return False

def read_student_records(filename):
"""Read all student records"""
students = []
try:
with open(filename, "r") as file:
for line in file:
try:
name, age, grade = line.strip().split(",")
students.append({
"name": name,
"age": int(age),
"grade": grade
})
except ValueError:
print(f"Warning: Invalid record format: {line.strip()}")
continue
return students
except FileNotFoundError:
print(f"No records file found. Starting fresh.")
return []
def display_students(students):
"""Display student records"""
if not students:
print("No student records found")
return

print("\n=== Student Records ===")


for i, student in enumerate(students, 1):
print(f"{i}. {student['name']} - Age: {student['age']} - Grade: {student['grade']}")

# Usage
students_file = "students.txt"

# Add some records


add_student_record(students_file, "Alice Johnson", 20, "A")
add_student_record(students_file, "Bob Smith", 21, "B")

# Read and display


all_students = read_student_records(students_file)
display_students(all_students)

Input Validation with Exception Handling

python
def get_integer_input(prompt, min_val=None, max_val=None):
"""Get validated integer input from user"""
while True:
try:
value = int(input(prompt))

if min_val is not None and value < min_val:


print(f"Value must be at least {min_val}")
continue

if max_val is not None and value > max_val:


print(f"Value must be at most {max_val}")
continue

return value

except ValueError:
print("Please enter a valid integer!")
except KeyboardInterrupt:
print("\nOperation cancelled by user")
return None

def get_file_input(prompt):
"""Get validated file path from user"""
while True:
try:
filename = input(prompt).strip()

if not filename:
print("Filename cannot be empty!")
continue
# Test if file can be opened
with open(filename, "r") as file:
pass # Just test opening

return filename

except FileNotFoundError:
print(f"File '{filename}' not found. Please try again.")
except PermissionError:
print(f"Permission denied for '{filename}'. Please try again.")
except KeyboardInterrupt:
print("\nOperation cancelled by user")
return None

# Usage
age = get_integer_input("Enter your age (0-120): ", 0, 120)
if age is not None:
print(f"Your age is {age}")

filename = get_file_input("Enter filename to read: ")


if filename:
print(f"Will process file: {filename}")

Quick Reference

File Operations
Read: with open("file.txt", "r") as f: content = f.read()
Write: with open("file.txt", "w") as f: f.write("text")
Append: with open("file.txt", "a") as f: f.write("text")
Exception Handling Structure

python

try:
# Code that might raise exception
pass
except SpecificException:
# Handle specific exception
pass
except Exception as e:
# Handle any other exception
pass
else:
# Runs if no exception occurred
pass
finally:
# Always runs (cleanup code)
pass

Common Exceptions
FileNotFoundError: File doesn't exist
PermissionError: No permission to access file

ValueError: Invalid value conversion

TypeError: Wrong data type

IndexError: Invalid list/string index


KeyError: Invalid dictionary key
ZeroDivisionError: Division by zero
Best Practices

Always use with statement for file operations


Handle specific exceptions before general ones

Use descriptive error messages


Don't ignore exceptions silently

Close files properly (automatic with with statement)

Handle files and exceptions safely for robust Python programs

You might also like