Skip to content

Commit 367ff33

Browse files
author
Whackbat
committed
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.
1 parent 8b18222 commit 367ff33

File tree

1 file changed

+3
-2
lines changed

1 file changed

+3
-2
lines changed

check_file.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
# Last Modified :
55
# Version : 1.0
66

7-
# Modifications :
7+
# Modifications : with statement added to ensure correct file closure
88

99
# Description : Check a file exists and that we can read the file
1010

@@ -14,7 +14,8 @@
1414
# Readfile Functions which open the file that is passed to the script
1515

1616
def readfile(filename):
17-
line = open(filename, 'r').read()
17+
with open(filename, 'r') as f: # Ensure file is correctly closed under all circumstances
18+
line = f.read()
1819
print line
1920

2021
def main():

0 commit comments

Comments
 (0)