DEV Community

Cover image for Day 3: File Handling and Error Handling
arjun
arjun

Posted on

Day 3: File Handling and Error Handling

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")
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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.")
Enter fullscreen mode Exit fullscreen mode

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.")
Enter fullscreen mode Exit fullscreen mode
  • ZeroDivisionError: Occurs when dividing by zero.
  try:
      result = 10 / 0
  except ZeroDivisionError:
      print("You cannot divide by zero!")
Enter fullscreen mode Exit fullscreen mode

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}")
Enter fullscreen mode Exit fullscreen mode

Conclusion

Today, we covered:

  1. File handling: Reading and writing files.
  2. Error handling: Using try-except to manage exceptions gracefully.
  3. 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)