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! 🚀

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay