def replace_nhs_numbers(fn, locations): outFn = os.path.join(os.path.dirname(fn), "ANON_" + os.path.basename(fn)) with open(fn, 'rb') as f, open(outFn, 'wb') as out: for location in locations: buf = f.read(location - f.tell()) out.write(buf) pseudo = str(get_pseudonym((int(f.read(10))))) out.write(pseudo) out.write(f.read())