Introduction
File handling allows reading and writing data to files, while exception handling ensures programs handle errors gracefully. This step will cover how to work with files and manage exceptions effectively in Python.
1. File Handling in Python
Python provides built-in functions for reading, writing, and managing files using the open()
function.
Opening and Closing Files
file = open("example.txt", "r") # Open file in read mode
print(file.read()) # Read contents
file.close() # Close file
Using the with
Statement (Automatic Closure)
with open("example.txt", "r") as file:
print(file.read())
2. Reading Files
Reading Entire File
with open("example.txt", "r") as file:
content = file.read()
print(content)
Reading Line by Line
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
Reading Specific Number of Characters
with open("example.txt", "r") as file:
print(file.read(10)) # Reads first 10 characters
3. Writing to Files
Writing to a New File (Overwrites Existing Content)
with open("example.txt", "w") as file:
file.write("Hello, Python!\nThis is a new file.")
Appending Data to an Existing File
with open("example.txt", "a") as file:
file.write("\nAppending new content.")
4. Exception Handling in Python
Errors can crash programs if not handled properly. Python uses try-except
blocks to catch exceptions.
Basic Exception Handling
try:
x = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
Handling Multiple Exceptions
try:
num = int(input("Enter a number: "))
result = 10 / num
except ValueError:
print("Error: Invalid input, enter a number.")
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
Using finally
Block (Always Executes)
try:
file = open("example.txt", "r")
print(file.read())
finally:
file.close()
print("File closed.")
5. Raising Custom Exceptions
Use raise
to define custom exceptions.
def check_age(age):
if age < 18:
raise ValueError("Age must be 18 or above.")
return "Access granted."
try:
print(check_age(15))
except ValueError as e:
print("Error:", e)
Exercises
- Write a program that reads a file and prints its contents.
- Create a script that writes user input to a text file.
- Modify a file by appending new data instead of overwriting it.
- Write a program that handles division by zero using
try-except
. - Implement a function that raises a custom exception when an invalid condition is met.
Conclusion
You have now learned file handling (reading, writing, appending files) and exception handling (try-except, raising custom exceptions) in Python. The next step is to explore working with libraries and APIs.