Search code examples
pythonread-write

How can I compute simple addition on multiple .xyz files?


I am currently trying to write a Python program that will take 2 existing .xyz files (containing 3 columns of values separated by spaces), loop through them, add numbers from equivalent positions in each column of the list, then write those values to a separate .txt file in the same position.

For example, if I have the list:

(line denoting number of atoms)
(comment line)
(atom symbol) 1 1 1
(atom symbol) 2 2 2
(atom symbol) 3 3 3

and the list:

(line denoting number of atoms)
(comment line)
(atom symbol) 3 3 3
(atom symbol) 2 2 2
(atom symbol) 1 1 1

I want to make python create a new file in the form:

(line denoting number of atoms)
(comment line)
(atom symbol) 4 4 4
(atom symbol) 4 4 4
(atom symbol) 4 4 4

Currently my is giving me the error:

TypeError: float() argument must be a string or a number

and my code is:

def sumen():
    infile_1 = input("Name of first file you wish to open as file using '.txt': ")
    infile_2 = input("Name of second file you wish to open as file using '.txt': ")
    outfile = input("Name the output file using '.txt': ")

    with open(infile_1, 'r') as myfile_1, open(infile_2, 'r') as myfile_2:
        for line1 in myfile_1.readlines():
            parts1 = line1.split('\n')
        for line2 in myfile_2.readlines():
            parts2 = line2.split('\n')

    with open(outfile, 'w') as outputfile:
        totalenergy = float(parts1) + float(parts2)

    print("The output was printed to:", outfile)

sumen()

Solution

  • Here's how I would do it:

    def sumen():
        infile_1 = input("Name of first file you wish to open as file using '.txt': ")
        infile_2 = input("Name of second file you wish to open as file using '.txt': ")
        outfile = input("Name the output file using '.txt': ")
    
        with open(infile_1, 'r') as myfile_1, \
             open(infile_2, 'r') as myfile_2, \
             open(outfile, 'w') as outputfile:
    
            for _ in range(2):  # copy first two lines of first file (and advance second)
                outputfile.write(next(myfile_1))
                next(myfile_2)
    
            for (line1, line2) in zip(myfile_1, myfile_2):
                parts1 = line1.split()
                parts2 = line2.split()
                totalenergy = [float(parts1[i]) + float(parts2[i]) for i in range(1, len(parts1))]
                outputfile.write('{} {}\n'.format(parts1[0], ' '.join(map(str, totalenergy))))
    
        print("The output was printed to:", outfile)
    
    sumen()
    

    For your sample input files, this will produce an output file that looks something like this:

    (line denoting number of atoms)
    (comment line)
    (atom symbol) 4.0 4.0 4.0
    (atom symbol) 4.0 4.0 4.0
    (atom symbol) 4.0 4.0 4.0