Rule Definition
When a file is opened by Python, resources are allocated until the file is closed. Thus it is important to ensure the file is closed as soon as the file manipulation is done by handling correctly potential exceptions. Delegating file closing to the underlying interpreter/compiler can have a negative impact on code portability and can result in unexpected behavior.
Remediation
Use the with statement to open a file, otherwise explicitly close opened files while correctly handling exceptions arising from file manipulation.
Violation Code Sample
>>> f = open("hello.txt",'w')
>>> f.write("world")
>>> f.close()
Fixed Code Sample
>>> f = open("hello.txt", 'w')
>>> try:
>>> f.write("world")
>>> finally:
>>> f.close()
# or even better
>>> with open("hello.txt", 'w') as f:
>>> f.write("world")
Reference
This rule is compliant with OMG CISQ ASCPEM-PRF-15, ASCRM-CWE-772 recommendations.
Related Technologies
Technical Criterion
PCI-DSS4-Requirement-6.2.4 - Software engineering techniques or other methods are defined and in use by software development personnel to prevent or mitigate common software attacks and related vulnerabilities
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.