在文件中进行算术操作

# 处理算数,并返回结果
def handleArithmetic(str):
# 去除等于号
arithmetic = str.split(‘=’)[0]
# 标记运算符 0为- 1为+
operator = 0
for ar in arithmetic:
if(ar ==’+’):
operator = 1
elif(ar ==’-‘):
operator = 0
if(operator ==0):
arithmeticList = arithmetic.split(‘-‘)
return (int(arithmeticList[0]) – int(arithmeticList[1]))
elif(operator==1):
arithmeticList = arithmetic.split(‘+’)
return (int(arithmeticList[0]) + int(arithmeticList[1]))
# 程序主入口
def main():
# 打开新文件,如果没有就创建一个
resultFile = open(‘E:\\test_calc_result.txt’,’w’)
with open(‘E:\\test_calc.txt’,’r’) as file:
# 读取文件行数,返回每行数据
lines = file.readlines()
# print(lines)
for line in lines:
# 去除换行符
lineNew = line.split(‘\n’)[0]
result =str(handleArithmetic(lineNew))
# 产生新的式子
newStr = lineNew+result
# 将文件写入新文件
resultFile.write(newStr+’\n’)
# 关闭文件
resultFile.close()
main()