Use the
with
statement to open a file 72
73 sorted(value, key=lambda k: len(k))
74
75 f = open("/tmp/.deepsource.toml", "r") 76 f.write("config file.")
77 f.close()
78
Description
Opening a file using with
statement is preferred as function open
implements the context manager protocol that releases the resource when it is outside of the with
block. Not doing so requires you to manually release the resource.
Bad practice
f = open('/tmp/.deepsource.toml', 'w')
f.write("config file.")
# No `f.close()` statement: file may remain unaccessible
Preferred:
with open('/tmp/.deepsource.toml', 'w') as f:
f.write("config file.")