You can use eval
to evaluate everything to the left of the equal sign.
with open('questions.txt') as fp:
qs = fp.readlines()
answers = [eval(q.split('=')[0]) for q in qs if q.strip()]
with open('answers.txt', 'w') as fp:
for q, a in zip(qs, answers):
fp.write(q.strip() + str(a) + '\n')
answers
is a list of the evaluated expressions on the left side of the equal sign. eval
takes whatever string is given to it and tries to run it as a command in Python. q.split('=')[0]
splits each question into two parts: everything to the left of the equal sign (part 0) and everything to the right (part 1). We are grabbing only the first part to evaluate. The rest of the line is iterating over the questions in your file and checking to make sure the line is not just a extra blank line.
Using zip
matches up each question q
to the corresponding answer a
, so the for loop yield both the first q and a, then second q and a, etc. fp
is a file object that we opened for writing. fp.write
tells python to write to disk the string argument. I am using q.strip()
to remove the newline characters, appending the answer as a string, and then adding a newline character to the end.