Simon Melouah
Simon Melouah

Reputation: 652

What is the correct way of using context managers to read files?

I'm wondering about the correct way of using context managers in Python for reading in files with additional logic that's dependent on the loaded in file - from a memory management and overall best practice perspective which of the below is better and why?

with open(my_file, "r") as fp:
   file_contents = fp.read().splitlines()
   for content in file_contents:
      print(content)

or

file_contents = []
with open(my_file, "r") as fp:
   file_contents = fp.read().splitlines()
for content in file_contents:
    print(content)

Upvotes: 0

Views: 1073

Answers (1)

DeepSpace
DeepSpace

Reputation: 81654

Expanding on my comments:

Memory wise both are the same.

However, the first example keeps the file open for longer (while reading and iterating), while the second one keeps the file open only while reading.

It might make a difference for very long files and if there is another process that waits to read or write to the file, otherwise the difference is neglectable.

Best-practice wise, I'd go with the second approach. If we can close the file early, we might as well do it.

Upvotes: 2

Related Questions