写入新文件的形式?

2024-09-12 10:28:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我被要求写一个程序,把一个包含简单数学练习的txt文件输入一个新的txt文件并给出答案 我的代码如下:

import sys
import os.path

pathex=input("input exercises file path ")
pathsol=input("Input solutions file path ")
if not(os.path.exists(pathex)):
    print("exercises file does not exist in the inputted directory ")
    if not (os.path.exists(pathsol)):
        print("solutions file does not exist in the inputted directory")
    sys.exit()

with open(pathsol,'w') as solutions:
    with open(pathex,'r') as exercises:
        for line in exercises:
            list = line.rstrip('\n').split(' ')
            if list[1]=='+':
                solutions.write(line + '='+ str(int(list[0])+int(list[2])))
            if list[1]=='-':
                solutions.write(line + '='+ str(int(list[0])-int(list[2])))
            if list[1]=='/':
                solutions.write(line + '='+ str(int(list[0])//int(list[2])))

我的练习文件如下:

6 + 4
15 - 3
14 / 14

我的解决方案文件只是一个空白的txt文件

预期结果是解决方案文件包含:

6 + 4 = 10
15 - 3 = 12
14 / 14 = 1

Tags: 文件pathtxtinputifoslinenot
1条回答
网友
1楼 · 发布于 2024-09-12 10:28:22

这里

import sys
import os.path
pathex=input("input exercises file path ")
pathsol=input("Input solutions file path ")
if not(os.path.exists(pathex)):
    print("exercises file does not exist in the inputted directory ")
    if not (os.path.exists(pathsol)):
        print("solutions file does not exist in the inputted directory")
    sys.exit()
math = open(pathex, "r")
math_sol = open(pathsol, "w+")

expressions = math.readlines()
for expression in expressions:
    symbols = expression.split()
    if symbols[1] == "+":
        math_sol.write(str(int(symbols[0]) + int(symbols[2])) + "\n")
    if symbols[1] == "-":
        math_sol.write(str(int(symbols[0]) - int(symbols[2]))+ "\n")
    if symbols[1] == "*":
        math_sol.write(str(int(symbols[0]) * int(symbols[2]))+ "\n")
    if symbols[1] == "/":
        math_sol.write(str(int(symbols[0]) / int(symbols[2]))+ "\n")
math_sol.close()
math.close()

相关问题 更多 >