Error Handling
When working with files, it’s important to handle potential errors that may occur during file operations. Common errors include file not found, permission denied, or disk full. You can use try-except blocks to catch and handle these errors gracefully.
try:
file_path = “my_file.txt”
file = open(file_path, “r”)
content = file.read()
print(“File content:”, content)
file.close()
except FileNotFoundError:
print(f”File ‘{file_path}’ not found!”)
except PermissionError:
print(f”Permission denied ‘{file_path}’!”)
except IOError as e:
print(f”I/O error occurred ‘{file_path}’:”, str(e))
except Exception as e:
print(“An error occurred:”, str(e))
In this example, we attempt to open a file named “my_file.txt” ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access