with
statement PTC-W0010with
statement to open a file136 Template_object = TemplateModel.objects.create(**data)
137 if Template_object.template == "null":
138 file = f"media/media/template/{data['html_file'].name}"
139 HTMLFile = open(file, "r")140 index = HTMLFile.read()
141 S = BeautifulSoup(index, "lxml")
142 Template_object.template = S.body.prettify()
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.
f = open('/tmp/.deepsource.toml', 'w')
f.write("config file.")
# No `f.close()` statement: file may remain unaccessible
with open('/tmp/.deepsource.toml', 'w') as f:
f.write("config file.")