Q:

Converting a text file with math problems to a text file with the answers to those problems

I am currently trying to work on a code that takes input from a user asking them to open a file with math problems within it, and then outputs a file with the answers to those problems. I have looked all over for some kind of solution to this, but these are the closest I have gotten:
text file contents:
2 + 2
3 * 3
4.5 - 2.3
-8.8 + 1.2
2 ^ 4
8.9 / 2.3
5 % 3
-2 * -2
Attempt 1:
input_file_name = input("What file would you like to open? ")
output_file_name = input("What file would you like to write to? ")

with open(input_file_name,"r") as input_file:
    contents = input_file.readlines()
    num = "".join(contents)
    contents_length = len(num)

with open(output_file_name, "w") as output_file:
    while contents_length >= 0:
        num = num.replace("^","**") # change the ^ to ** so python can properly do the function
        contents_value = exec(num)

        contents_length = contents_length - 1

    output_file.write(str(contents_value))

The text file I received would return "None"
Attempt 2:
input_file_name = input("What file would you like to open? ")
output_file_name = input("What file would you like to write to? ")

infile = open(input_file_name, "r")
outfile = open(output_file_name, "w")

lines = infile.readlines()

i = len(lines) - 1

while i >= 0:
    ans = eval(lines[i])
    outfile.write(str(ans))
    i = i - 1

infile.close()
outfile.close()

And the text document had 423.86956521739130476-7.60000000000000052.294 in the file.
So, I'm not really sure what else to do. Any help will be greatly appreciated.

A:

You need to process each line separately, but this code
num = "".join(contents)

combines all the lines into a single string.
The other problem is the unwanted decimal places. You can fix that using the round function. The code below reads the data directly from the script, but it's easy enough to adapt it to reading the data from the file, either with .readlines, or by simply looping over the file object. 
data = '''\
2 + 2
3 * 3
4.5 - 2.3
-8.8 + 1.2
2 ^ 4
8.9 / 2.3
5 % 3
-2 * -2
'''.splitlines()

for line in data:
    line = line.replace('^', '**')
    s = round(eval(line), 6)
    print(s)

output
4
9
2.2
-7.6
16
3.869565
2
4

That output was created using Python 3. On Python 2, it's not quite as clean: everything will be written as a float.
Python 2 output
4.0
9.0
2.2
-7.6
16.0
3.869565
2.0
4.0

I assume that you're aware that eval and exec should generally be avoided because they can be a security risk. For details, please see Eval really is dangerous by SO veteran Ned Batchelder. But I guess you don't have much choice here, and you can guarantee that the input file won't contain malicious code.          

