refactor to use context managers

This commit is contained in:
Daira Hopwood 2016-04-12 15:48:24 +01:00 committed by Brian Warner
parent ec37d52942
commit 504e0d02f3
1 changed files with 3 additions and 13 deletions

View File

@ -274,11 +274,8 @@ def move_into_place(source, dest):
os.rename(source, dest) os.rename(source, dest)
def write_atomically(target, contents, mode="b"): def write_atomically(target, contents, mode="b"):
f = open(target+".tmp", "w"+mode) with open(target+".tmp", "w"+mode) as f:
try:
f.write(contents) f.write(contents)
finally:
f.close()
move_into_place(target+".tmp", target) move_into_place(target+".tmp", target)
def write(path, data, mode="wb"): def write(path, data, mode="wb"):
@ -286,26 +283,19 @@ def write(path, data, mode="wb"):
f.write(data) f.write(data)
def read(path): def read(path):
rf = open(path, "rb") with open(path, "rb") as rf:
try:
return rf.read() return rf.read()
finally:
rf.close()
def put_file(path, inf): def put_file(path, inf):
precondition_abspath(path) precondition_abspath(path)
# TODO: create temporary file and move into place? # TODO: create temporary file and move into place?
outf = open(path, "wb") with open(path, "wb") as outf:
try:
while True: while True:
data = inf.read(32768) data = inf.read(32768)
if not data: if not data:
break break
outf.write(data) outf.write(data)
finally:
outf.close()
def precondition_abspath(path): def precondition_abspath(path):
if not isinstance(path, unicode): if not isinstance(path, unicode):