To do this at the place of change, you can fileinput module ( print prints to a file, see. How to replace a line in a .txt file with python 3? ):
#!/usr/bin/env python3 from fileinput import FileInput from math import inf with FileInput('numbers.txt', inplace=True, backup='.bak') as numbers_file, \ open('bins.txt') as bins_file: bins = map(float, bins_file) b = next(bins) # assume sorted and all numbers are within bins range for x in map(float, numbers_file): while x > b: b = next(bins) if x == b: x = nextafter(x, -inf) # previous print(x)
Result :
0.12 0.32 0.43999999999999995 0.56 0.5999999999999999
Here the nextafter() function is used to find a float that is smaller than the specified one. On CPython, you can borrow it from the C library:
import ctypes libc = ctypes.CDLL(None) nextafter = libc.nextafter nextafter.restype = ctypes.c_double nextafter.argtypes = [ctypes.c_double, ctypes.c_double]
To get the result as in question, you can define: nextafter = lambda x, y: x - .001