pythonfilebetweenoperations

Calculating the quotient between two files and writing it into another file


Using Python, I have two large (equally long) files in which the numbers are divided by spaces:

0.11158E-13 0.11195E-13 0.11233E-13 ... # file1

0.11010E-13 0.11070E-13 0.11117E-13 ... # file2

There are differences in the values and I would like to get the relative differences and writing them in the same format into a third file. I can do it for the first value but have problem when it comes to ITERATING the process (so that all values are computed).

This is the code (I am new to the python code):

with open('ex1.idl', 'r') as f1:      #this opens the first file
    with open('ex2.idl', 'r') as f2:      #this opens the second file

        f1 = f1.read(13)          # reading the length of the value (ex1.idl)
        f2 = f2.read(13)          # reading the length of the value (ex2.idl)
        f1 = float(f1)          #assigning the numerical value for the string
        f2 = float(f2)          #assigning the numerical value for the string
        c = f1/f2               #calculating relative values    

with open('ex3.txt', 'w') as f3:          #opening the new file and
    f3.write(str(c))                      #writing into the new file as a string

Is this the way to go or should I go with a different approach? An answer is very much appreciated.


Solution

  • It looks like your files have one line each. So the easiest way to get the numbers in each file is to just read the entire content of the file, strip any unneeded characters and then split on the whitespace separating the floating point values. Splitting on the space will give you a list of strings, which you can then coerce to floats. At this point, you should have two lists of floating point values, and that is when you use the combination of the zip and map functions to carry out the division operation. The following is an illustration:

    with open('ex1.idl') as f1, open('ex2.idl') as f2:
        with open('ex3.txt', 'w') as f3:
            f1 = map(float, f1.read().strip().split())
            f2 = map(float, f2.read().strip().split())
            for result in map(lambda v: v[0]/v[1], zip(f1, f2)):
                # This writes the results all in one line
                # If you wanted to write them in multiple lines,
                # then you would need replace the space character
                # with a newline character.
                f3.write(str(result)+" ")
    

    I hope this proves useful.