try:
with open('example.txt', 'r') as file:
# Loop through the lines of the file and print each one
for line in file:
print(line)
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. for
` loop is used to iterate over the lines of the file one by one. Inside the loop, each line is printed to the console.for
` loop automatically reads each line of the file until it reaches the end. This is a convenient way to read the entire file without having to worry about how many lines it contains. If you need to keep track of the line number, you can use the `enumerate()
` function, like this :try:
with open('example.txt', 'r') as file:
# Loop through the lines of the file and print each one with its line number
for i, line in enumerate(file):
print(f"Line {i+1}: {line}")
except FileNotFoundError as e:
print(f"File not found: {e}")
except Exception as e:
print(f"An error occurred: {e}")
enumerate()
` function is used to generate a sequence of tuples, where the first element of each tuple is the line number (starting at 1) and the second element is the line itself. i
` and `line
` variables inside the `for
` loop, and the line number and line contents are printed to the console for each iteration.