文件并非始终关闭¶
ID: py/file-not-closed
Kind: problem
Security severity:
Severity: warning
Precision: medium
Tags:
- efficiency
- correctness
- resources
- external/cwe/cwe-772
Query suites:
- python-security-and-quality.qls
如果打开文件,则应始终将其关闭,即使引发了异常。未能确保所有文件都关闭可能会导致由于打开文件过多而导致失败。
建议¶
确保如果打开文件,则始终在退出方法时关闭它。将 open()
和 close()
函数之间的代码包装在 with
语句中,或者使用 try...finally
语句。优先使用 with
语句,因为它更短且更易读。
示例¶
以下代码展示了关闭文件的不同方法示例。在第一个示例中,只有在方法成功退出时才关闭文件。在其他示例中,在退出方法时始终关闭文件。
f = open("filename")
... # Actions to perform on file
f.close()
# File only closed if actions are completed successfully
with open("filename") as f:
...# Actions to perform on file
# File always closed
f = open("filename")
try:
... # Actions to perform on file
finally:
f.close()
# File always closed