-3

I have a task to open file input.txt, which contains two lines:

100-50
50-25

Then I need to perform subtraction (evaluate the given expresions) and write them in output.txt. The output should look like this:

100-50=50
50-25=25

So far I have this:

with open('input.txt','r') as file1:
    x=file1.read()
    print(x)

But I don't know how to proceed with evaluating given input.

STerliakov
  • 4,983
  • 3
  • 15
  • 37
Milo
  • 1
  • 2

1 Answers1

-1
with open('input.txt','r') as f1:
    lines = f1.readlines()
    with open('output.txt', 'w') as f2:
        for line in lines:
            sub = int(line.split("-")[0]) - int(line.split("-")[1])
            f2.write(line.replace("\n", "") + "=" + str(sub) + "\n")
dimple
  • 158
  • 8
  • 1
    Since you're using a context manager to open `f1`, you don't need to call `f1.close()`. You should simply move the next block out of the context manager, i.e., `with open('output...` and the rest should be outdented one level. Same thing with `f2`, `f2.close()` is superfluous when using a context manager (i.e., a `with` statement). – joanis Dec 18 '22 at 16:25
  • Thanks a lot, nicely explained! Really appreciate. – Milo Dec 18 '22 at 16:34
  • Louis I can't explain how helpful it was, and really nicely explained, very easy to understand. After all I guess Python is not so scary. – Milo Dec 18 '22 at 16:39
  • I don't think this is useful. This code doesn't work for any expression that isn't in the form ` - `. For example, other binary operators, unary operators (e.g. a leading `-`), more than one operator in an expression, operator precedence, brackets, etc. It is impractical to use this approach with more complicated expressions. If this all that the OP needs ... OK. But then this answer is unlikely to help anyone other than the OP. – Stephen C Dec 19 '22 at 04:05
  • Thanks to joanis's comment. Actually don't need to use `close()` function. – dimple Dec 19 '22 at 12:54