I have two files:

1.txt

 0.12 0.32 0.44 0.56 0.60 

2.txt

 0.13 0.44 0.60 

Need to change the file 1.txt to the following:

 0.12 0.32 0.439 0.56 0.599 

where 0.599 can have any number of decimal places. The main task is to be less than 0.60.

My code is:

 with open('1.txt') as phone_file, \ open('2.txt') as syl_file: for line_p in phone_file: for line_s in syl_file: if line_p == line_s: line_p = line_s-0.001 print(line_p) 

    4 answers 4

     output = [] # Список выходных строк with open('1.txt') as phone_file, \ open('2.txt') as syl_file: # Вытаскиваем строки из текстовых файлов, # обрезая перевод строки и пробелы p_lines = [line.strip() for line in phone_file] s_lines = [line.strip() for line in syl_file] for line_p in p_lines: new_p = float(line_p)-0.001 if line_p in s_lines else float(line_p) output.append(str(new_p)) # Теперь открываем файл только для записи with open('1.txt', 'w') as phone_file: for line in output: # И вставляем в него получившиеся числа phone_file.write(str(line) + '\n') 

      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

        Using the Pandas module:

         import pandas as pd # read up files into Pandas.Series variables s1 = pd.read_csv(r'1.txt', header=None, squeeze=True) s2 = pd.read_csv(r'2.txt', header=None, squeeze=True) delta = 1e-6 # subtract [delta] from matchig elements s1.loc[s1.isin(s2)] -= delta # overwrite [1.txt] with modified data s1.to_csv(r'1.txt', header=None, index=False) 

        Contents of the updated file:

         In [14]: print(open(r'1.txt').read()) 0.12 0.32 0.43999900000000003 0.56 0.599999 

          You can numpy.isin(a, b) to find out which elements from a are equal to elements from b (which values ​​need to be reduced in the current task):

           #!/usr/bin/env python import numpy as np a = np.loadtxt('numbers.txt') bins = np.loadtxt('bins.txt') a[np.isin(a, bins)] -= .001 np.savetxt('output.txt', a, '%g') 

          Conclusion:

           0.12 0.32 0.439 0.56 0.599 

          A variant that uses the fact that the items are sorted by calling numpy.searchsorted() :

           #!/usr/bin/env python import numpy as np a = np.loadtxt('numbers.txt') bins = np.loadtxt('bins.txt') ind = np.searchsorted(a, bins) eq = a[ind] eq[eq == bins] -= .001 a[ind] = eq np.savetxt('output.txt', a, '%g') 

          The same result.