From d73b162b70e60f64591b2f6df68ca8be6b868baa Mon Sep 17 00:00:00 2001 From: Ethan McCue Date: Wed, 27 Apr 2022 20:07:27 -0400 Subject: [PATCH] Use `with` to automatically close file The pattern of ```python file = open("path", "r") # ... do stuff with file ... file.close() ``` Is subtly flawed in that if an error happens between opening the file and closing it, you will never reach the line that closes the file. This doesn't matter if the next thing your code does is crash entirely, but if you have a longer running app (like a web server) then this would be a "resource leak" --- main.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/main.py b/main.py index c60e8cd..10ed36f 100644 --- a/main.py +++ b/main.py @@ -25,9 +25,8 @@ print(postString) -sample = open("data.txt", "r", errors="ignore") -data = sample.read() -sample.close() +with open("data.txt", "r", errors="ignore") as sample: + data = sample.read() data = (data .lower() @@ -79,4 +78,4 @@ def generateStatement(wordCount): for _ in range(1): print(generateStatement(wordCount)) - \ No newline at end of file +