Search code examples
python-3.xevalwith-statement

Reading operations line by line and making eval() for each line


So I'm trying to read the operations from text file and do them in python using eval() function. Everything is okay as long as it is one operation, but when I have two or more operations it doesn't work as intended

import math
with open('operations.txt', 'r') as f:
    line = f.read()
    line = (eval(line))
    line = (eval(line))
    print(line)

In my text file I've two lines

  • 2 + 2 * 4 (work as intended)
  • 4 / 2 (when I add it to python it crashes entire program)

Could anyone give me some advice. How can I read all lines and do eval() for each of them? I'm trying to do it universal so if let's say I give 10 different operations, I'd like to get result for each of them and save them in other text file.


Solution

  • I assume you want to iterate over the lines in your file:

    with open('operations.txt', 'r') as f:
        for line in f.readlines()
            result = eval(line)
            ...
    

    See also the Python doc on that topic.

    Comment: The reason it crashes is because it tries to evaluate the entire file as one command, i.e. eval('2+2*4\n4/2'), which is not Python code