File and Error Handling
Pythons Tutorials
Files
Python allows you to read from and write to external files, enabling your programs to interact with data beyond the code.
1. Reading from Files:
You can open a file, read its contents, and process the information using Python’s built-in file-handling capabilities.
Example: Reading from a File
# Opening a file in read mode
file = open("data.txt", "r")
# Reading and printing the file's content
content = file.read()
print(content)
# Closing the file
file.close()
2. Writing to Files:
You can also create new files or overwrite existing ones with fresh data.
Example: Writing to a File
# Opening a file in write mode
file = open("output.txt", "w")
# Writing content to the file
file.write("Hello, world!")
# Closing the file
file.close()
Errors
Errors happen, but Python’s exception handling allows you to anticipate and manage them, ensuring your program doesn’t crash unexpectedly.
Example: Using Exception Handling
try:
x = 10 / 0
except ZeroDivisionError:
print("Oops! Division by zero is not allowed.")
Using “Try” and “Except”:
Python’s “try” and “except” blocks provide a way to gracefully handle errors and continue execution.
Example: Using “Try” and “Except”
try:
age = int(input("Enter your age: "))
except ValueError:
print("Oops! That's not a valid age.")
print("Program continues...")
Using the “Finally” Block:
The “finally” block ensures that specific code is executed regardless of whether an exception occurred.
Example: Using “Finally” Block
In this case the file will be closed whether there is an exception or not.
try:
file = open("data.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found.")
finally:
file.close()