CodeQL documentation

File is not always closed

ID: py/file-not-closed
Kind: problem
Severity: warning
Precision: medium
   - efficiency
   - correctness
   - resources
   - external/cwe/cwe-772
Query suites:
   - python-security-and-quality.qls

Click to see the query in the CodeQL repository

If a file is opened then it should always be closed again, even if an exception is raised. Failing to ensure that all files are closed may result in failure due to too many open files.


Ensure that if you open a file it is always closed on exiting the method. Wrap the code between the open() and close() functions in a with statement or use a try...finally statement. Using a with statement is preferred as it is shorter and more readable.


The following code shows examples of different ways of closing a file. In the first example, the file is closed only if the method is exited successfully. In the other examples, the file is always closed on exiting the method.

f = open("filename")
    ... # Actions to perform on file
# File only closed if actions are completed successfully

with open("filename") as f:
    ...# Actions to perform on file
# File always closed

f = open("filename")
    ... # Actions to perform on file
# File always closed