celani99
celani99

Reputation: 29

Unable to get sum to print in outfile

I am attempting to create a program that will sum corresponding values in separate lists and write a new file with the calculated sum. For example, I have infile_1.txt with 10 items and infile_2.txt also with 10 items. The goal is to take the first number from infile_1.txt, add it to the first number of infile_2 and create a new text file with the sum of the two numbers. The two files are in the same folder as my program, so Python recognizes them and prints the new file to the folder as well. The code I am using is below:

def sumen():
outfile = input("Name the output file: ")
myfile_1 = open("infile_1.txt",'r')
myfile_2 = open("infile_2.txt",'r')
outputfile = open(outfile, 'w')
for line in myfile_1:
    readfile1 = myfile_1.readline()
    readfile2 = myfile_2.readline()
    totalenergy = myfile_1[0:] + myfile_2[0:]
    print(totalenergy,file=outputfile)
myfile_1.close()
myfile_2.close()
outputfile.close()
sumen()

When I run the program it allows me to choose the outfile (totalenergy.txt), and then it ends. I've checked the file that Python creates and there is nothing written in it.

Currently, I am experiencing the error "totalenergy = myfile_1[0:] + myfile_2[0:] TypeError: '_io.TextIOWrapper' object is not subscriptable". I've also encountered an Attribute Error that had to do with the closing of the infiles and the outfile that said " 'str' has no attribute 'close' "

One additional question: If the two files differ in length, is it possible to rewrite the for loop to account for the difference in length? Another thing I'm wondering about is if the line totalenergy = myfile_1[0:] + myfile_2[0:]is correct in the sense of Python grabbing the next value in each list during each consecutive iteration.

I am relatively new at python, so any help would be greatly appreciated. Thanks.

Upvotes: 0

Views: 62

Answers (1)

Barmar
Barmar

Reputation: 781141

When you do for line in myfile_1:, that reads the file, so myfile_1.readline() gets the next line. You don't need the second statement.

Also, readfile1 and readfile2 will be strings. If you want to add them as integers, you need to call int() to convert them.

for readfile1 in myfile_1:
    readfile2 = myfile_2.readline()
    totalenergy = int(readfile1) + int(readfile2)
    print(totalenergy,file=outputfile)

See How to cleanly loop over two files in parallel in Python for other ways to write this loop.

Upvotes: 1

Related Questions