Use the
with
statement to open a file36 for _ in range(len(result)):
37 dataNew.update({result[_]["title"]: int(result[_]["revisions"][0]["timestamp"][:4] + result[_]["revisions"][0]["timestamp"][5:7] + result[_]["revisions"][0]
38 ["timestamp"][8:10] + result[_]["revisions"][0]["timestamp"][11:13] + result[_]["revisions"][0]["timestamp"][14:16] + result[_]["revisions"][0]["timestamp"][17:19])})
39 open("/Users/emmm/Desktop/明日方舟/讨论监视.json",40 "w").write(dumps(dataNew, indent=4, ensure_ascii=False))
41
42 for k, v in dataNew.items():
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.")