Day 3: File Handling and Error Handling
Continuing from where we left off, today’s focus is on file handling and error management in Python. Understanding these concepts will help you manage data and handle unexpected scenarios gracefully. Let’s dive in!
File Handling in Python
Reading and Writing Files
1. Writing to a File
Use the open()
function with mode 'w'
(write) or 'a'
(append) to save data to a file.
with open("user_log.txt", "w") as file:
file.write("User logged in at 10:00 AM.\n")
2. Reading from a File
Use mode 'r'
(read) to access data.
with open("user_log.txt", "r") as file:
content = file.read()
print(content)
Error Handling in Python
Using Try-Except for Error Handling
Error handling allows your program to respond to issues without crashing.
try:
number = int(input("Enter a number: "))
print(f"The number you entered is {number}.")
except ValueError:
print("Invalid input! Please enter a valid number.")
Common Exceptions and How to Handle Them
-
FileNotFoundError
: Occurs when trying to read a non-existent file.
try:
with open("missing_file.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("The file does not exist.")
-
ZeroDivisionError
: Occurs when dividing by zero.
try:
result = 10 / 0
except ZeroDivisionError:
print("You cannot divide by zero!")
Project: User Input Logger
Build a small application that logs user inputs into a file.
try:
with open("user_log.txt", "a") as file:
while True:
user_input = input("Enter something (type 'exit' to quit): ")
if user_input.lower() == "exit":
break
file.write(user_input + "\n")
except Exception as e:
print(f"An error occurred: {e}")
Conclusion
Today, we covered:
- File handling: Reading and writing files.
-
Error handling: Using
try-except
to manage exceptions gracefully. - Practical project: Logging user inputs into a file for better understanding.
Practice these examples and try tweaking them for better insight. See you next time for more Python learning! 🚀
Top comments (0)