Home >Backend Development >Python Tutorial >Day 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!
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 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.")
try: with open("missing_file.txt", "r") as file: content = file.read() except FileNotFoundError: print("The file does not exist.")
try: result = 10 / 0 except ZeroDivisionError: print("You cannot divide by zero!")
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}")
Today, we covered:
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!