Home >Backend Development >Python Tutorial >Day File Handling and Error Handling

Day File Handling and Error Handling

Linda Hamilton
Linda HamiltonOriginal
2024-12-07 05:30:15263browse

Day 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")

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:

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

The above is the detailed content of Day File Handling and Error Handling. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn