Skip to content

Instantly share code, notes, and snippets.

@ephsmith
Created October 3, 2018 15:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ephsmith/cc4bf6622262e8968ad94f63fe6c45ce to your computer and use it in GitHub Desktop.
Save ephsmith/cc4bf6622262e8968ad94f63fe6c45ce to your computer and use it in GitHub Desktop.
Subtract values for params in one file from another and save the result to a new file.
#!/usr/bin/env python3
import argparse
def read(f):
"""Reads the contents of param=value file and returns a dict"""
d = {}
with open(f,'r') as fin:
for item in fin.readlines():
s = item.split('=')
d[s[0]] = int(s[1])
return d
def write(f, d):
"""Writes dict d to param=value file 'f'"""
with open(f, 'w') as fout:
for k,v in sorted(d.items()):
fout.write('{}={}\n'.format(k,v))
def subtract(d1, d2):
"""
Subtracts values in d2 from d1 for all params and returns the result in result.
If an item is present in one of the inputs and not the other, it is added to
d3.
"""
# Create a set of all possible keys
all_keys = set(d1.keys())
all_keys.update(d2.keys())
result = {}
for key in all_keys:
if key not in d1:
result[key] = d2[key]
elif key not in d2:
result[key] = d1[key]
else:
result[key] = d1[key] - d2[key]
return result
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('file1', type=str, help='path to file 1')
parser.add_argument('file2', type=str, help='path to file 2')
parser.add_argument('outfile', type=str, help='path to output file')
args = parser.parse_args()
d1 = read(args.file1)
d2 = read(args.file2)
d3 = subtract(d1,d2)
write(args.outfile, d3)
@ephsmith
Copy link
Author

ephsmith commented Oct 3, 2018

This script does account for parameters that may be in only one of the input files.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment