try:
with open('example.txt', 'r') as file:
# Read one line of the file
line = file.readline()
print("One line of the 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. The `readline()
` method is used to read one line of the file into the `line` variable.readline()
` method reads until it reaches a newline character (`\n
`) or the end of the file, whichever comes first. If the file does not contain any newline characters, the entire file will be read as a single line.try:
with open('example.txt', 'r') as file:
# Read and print each line of the file
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}")
for
` loop is used to iterate over the lines of the file one by one. Each line is printed to the console. This approach is useful if you want to read the entire file or a specific subset of lines.