try:
with open('example.txt', 'r') as file:
contents = file.read()
print(contents)
except FileNotFoundError as e:
print(f"File not found: {e}")
except Exception as e:
print(f"An error occurred: {e}")
open()
` function is used to open the file named "example.txt
" in read-only mode, and the `with
` statement is used to ensure that the file is properly closed after it has been read. contents
` variable using the `read()
` method. Finally, the contents are printed to the console.try
` block is used to catch any exceptions that might occur while reading the file, such as a `FileNotFoundError
` if the file does not exist, or an `IOError
` if there is a problem with reading the file. except
` block is executed instead, which prints an error message.example.txt
" with the file path of the file you want to read. Make sure that the file is in the same directory as your Python script, or provide the full path to the file if it is located elsewhere.