From 413dfa7273c9f97b9c095c6c2ce50ba0a608c89e Mon Sep 17 00:00:00 2001 From: Alex Trevino Date: Thu, 16 Feb 2017 09:41:55 -0500 Subject: [PATCH] [cloud][aws] Use `with` statement for file rw in EC2 dynamic inventory (#21390) * Use with statement when doing rw on files * Deserialize file-like object directly instead of a string For python 2/3 compatibility reasons, per PR feedback. --- contrib/inventory/ec2.py | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/contrib/inventory/ec2.py b/contrib/inventory/ec2.py index 9b9db4bafc..31e90f20d4 100755 --- a/contrib/inventory/ec2.py +++ b/contrib/inventory/ec2.py @@ -1519,26 +1519,22 @@ class Ec2Inventory(object): ''' Reads the inventory from the cache file and returns it as a JSON object ''' - cache = open(self.cache_path_cache, 'r') - json_inventory = cache.read() - return json_inventory - + with open(self.cache_path_cache, 'r') as f: + json_inventory = f.read() + return json_inventory def load_index_from_cache(self): ''' Reads the index from the cache file sets self.index ''' - cache = open(self.cache_path_index, 'r') - json_index = cache.read() - self.index = json.loads(json_index) - + with open(self.cache_path_index, 'r') as f: + self.index = json.load(f) def write_to_cache(self, data, filename): ''' Writes data in JSON format to a file ''' json_data = self.json_format_dict(data, True) - cache = open(filename, 'w') - cache.write(json_data) - cache.close() + with open(filename, 'w') as f: + f.write(json_data) def uncammelize(self, key): temp = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', key)