Junior — Middle
How is error handling implemented when reading and writing files in applications?
sobes.tech AI
Answer from AI
In Python, error handling when reading and writing files is usually implemented using the try-except construct, which allows catching exceptions that occur during file operations, such as FileNotFoundError, IOError, and others. It is also recommended to use the with context manager for automatic file closing, which reduces the likelihood of errors.
Example:
try:
with open('example.txt', 'r') as file:
data = file.read()
except FileNotFoundError:
print('File not found.')
except IOError:
print('Input/output error when working with the file.')
This approach allows safe file handling and proper error processing.