I am learning how to open text files in python and I was trying the following code:
from pathlib import Path
file_path = Path(r'path\to\file.txt')
with open(file_path) as file_object:
for line in file_object:
print(line)
contents = file_object.read()
print(contents)
Let's say file.txt contains three words, each on a separate line. The for loop executes normally and prints the three lines, however an empty string gets assigned to the variable "contents" and thus nothing is shown by the print statement at the end.
I am guessing the file is closed when the first statement after "with" is executed?
Thank you for your help!