Use the "with" keyword when dealing with file objects

It is good practice to use the "with" keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks
This commit is contained in:
deix
2017-08-28 17:20:38 +02:00
parent aa75970ad1
commit d9330ef698
6 changed files with 19 additions and 31 deletions

View File

@@ -27,17 +27,15 @@ class CrackResult(object):
name = CrackResult.cracked_file
json = []
if os.path.exists(name):
f = open(name, 'r')
text = f.read()
f.close()
with open(name, 'r') as fid:
text = fid.read()
try:
json = loads(text)
except Exception, e:
Color.pl('{!} error while loading %s: %s' % (name, str(e)))
json.append(self.to_dict())
f = open(name, 'w')
f.write(dumps(json, indent=2))
f.close()
with open(name, 'w') as fid:
fid.write(dumps(json, indent=2))
Color.pl('{+} saved crack result to {C}%s{W} ({G}%d total{W})'
% (name, len(json)))