-1

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!

houss
  • 7
  • 4

1 Answers1

1

After the for loop, the "current position" is at the end of the file. The .read() call reads the rest of the file, which is nothing (because it's already at the end). The file is still open, so it's not an error, there's just nothing more to read, because it's all been read already.

If you want to read the file again, you need to call .seek(0) to return the "current position" back to the beginning of the file.

Jiří Baum
  • 6,697
  • 2
  • 17
  • 17
  • 1
    Thank you for the answer. I couldn't find the a similar question since I didn't realize that the code was indeed "iterating" on the file. Keywords are tricky... – houss Aug 25 '20 at 13:02