From 367ff3346d23f0bdd273346ead7e41103b42ae50 Mon Sep 17 00:00:00 2001 From: Whackbat Date: Thu, 21 Jul 2016 10:29:33 +0100 Subject: [PATCH] Enforce correct file closure with statement added to ensure file is correctly closed under all circumstances. Although CPython will garbage collect the file object following the read operation, other implementations of Python may not. The file often is not immediately closed and is left to be disguarded at a later unknown point of execution. Additionally, in Python 3.2 or above the current implementation will throw a ResourceWarning exception which must otherwise be caught if enabled. Better safe than sorry. --- check_file.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/check_file.py b/check_file.py index 290429d7964..59eea2805b3 100644 --- a/check_file.py +++ b/check_file.py @@ -4,7 +4,7 @@ # Last Modified : # Version : 1.0 -# Modifications : +# Modifications : with statement added to ensure correct file closure # Description : Check a file exists and that we can read the file @@ -14,7 +14,8 @@ # Readfile Functions which open the file that is passed to the script def readfile(filename): - line = open(filename, 'r').read() + with open(filename, 'r') as f: # Ensure file is correctly closed under all circumstances + line = f.read() print line def main():