I was adding functionality to a prewritten code. I found a file was opened but never closed.
The code earlier was (problem on last line)
def scatter():
meta = request.json['metadata']
df = pd.DataFrame.from_records(request.json['data'])
df.reset_index(inplace=True, level=0)
sns.set_style("darkgrid", {"axes.facecolor": "0.9"})
plot = sns.scatterplot(data=df, x='x',
y='y', palette=PALLETE)
plt.xticks(rotation=45)
plt.xlabel(meta['X'])
plt.ylabel(meta['Y'])
plt.tight_layout()
plot.figure.savefig('scatter.png')
plt.clf()
return base64.b64encode(open('multibar.png', 'rb').read())
I changed last line to
with open('multibar.png', 'rb') as f:
return base64.b64encode(f.read())
Which code is much better? Was the file opened in the previous code, being closed implicitly (i.e. there is not need to close it)? If yes, how? If no, the function returns after opening the file, will there be any problem if file is not closed?