Use with statement.

This commit is contained in:
Bastian Kleineidam 2013-02-20 21:16:47 +01:00
parent 39c23ddf37
commit d0b5f254bb
2 changed files with 4 additions and 16 deletions

View File

@ -32,14 +32,11 @@ def extract_bzip2 (archive, compression, cmd, **kwargs):
targetname = util.get_single_outfile(outdir, archive) targetname = util.get_single_outfile(outdir, archive)
bz2file = bz2.BZ2File(archive) bz2file = bz2.BZ2File(archive)
try: try:
targetfile = open(targetname, 'wb') with open(targetname, 'wb') as targetfile:
try:
data = bz2file.read(READ_SIZE_BYTES) data = bz2file.read(READ_SIZE_BYTES)
while data: while data:
targetfile.write(data) targetfile.write(data)
data = bz2file.read(READ_SIZE_BYTES) data = bz2file.read(READ_SIZE_BYTES)
finally:
targetfile.close()
finally: finally:
bz2file.close() bz2file.close()
if verbose: if verbose:
@ -57,16 +54,13 @@ def create_bzip2 (archive, compression, cmd, *args, **kwargs):
bz2file = bz2.BZ2File(archive, 'wb') bz2file = bz2.BZ2File(archive, 'wb')
try: try:
filename = args[0] filename = args[0]
srcfile = open(filename) with open(filename) as srcfile:
try:
data = srcfile.read(READ_SIZE_BYTES) data = srcfile.read(READ_SIZE_BYTES)
while data: while data:
bz2file.write(data) bz2file.write(data)
data = srcfile.read(READ_SIZE_BYTES) data = srcfile.read(READ_SIZE_BYTES)
if verbose: if verbose:
util.log_info('... added %s' % filename) util.log_info('... added %s' % filename)
finally:
srcfile.close()
finally: finally:
bz2file.close() bz2file.close()
return None return None

View File

@ -30,14 +30,11 @@ def extract_gzip (archive, compression, cmd, **kwargs):
targetname = util.get_single_outfile(outdir, archive) targetname = util.get_single_outfile(outdir, archive)
gzipfile = gzip.GzipFile(archive) gzipfile = gzip.GzipFile(archive)
try: try:
targetfile = open(targetname, 'wb') with open(targetname, 'wb') as targetfile:
try:
data = gzipfile.read(READ_SIZE_BYTES) data = gzipfile.read(READ_SIZE_BYTES)
while data: while data:
targetfile.write(data) targetfile.write(data)
data = gzipfile.read(READ_SIZE_BYTES) data = gzipfile.read(READ_SIZE_BYTES)
finally:
targetfile.close()
finally: finally:
gzipfile.close() gzipfile.close()
if verbose: if verbose:
@ -55,16 +52,13 @@ def create_gzip (archive, compression, cmd, *args, **kwargs):
gzipfile = gzip.GzipFile(archive, 'wb') gzipfile = gzip.GzipFile(archive, 'wb')
try: try:
filename = args[0] filename = args[0]
srcfile = open(filename) with open(filename) as srcfile:
try:
data = srcfile.read(READ_SIZE_BYTES) data = srcfile.read(READ_SIZE_BYTES)
while data: while data:
gzipfile.write(data) gzipfile.write(data)
data = srcfile.read(READ_SIZE_BYTES) data = srcfile.read(READ_SIZE_BYTES)
if verbose: if verbose:
util.log_info('... added %s' % filename) util.log_info('... added %s' % filename)
finally:
srcfile.close()
finally: finally:
gzipfile.close() gzipfile.close()
return None return None