You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python计算器进阶:读取文本文件计算及异常处理问题求助

解决方案

一、修复文件不存在时的重试逻辑

原代码存在缩进错误、文件对象误用的问题,且未实现重试输入逻辑。可以通过while循环实现持续请求输入,直到用户提供有效的文件名:

choice2 = input("Would you like to use your own file for calculations or enter a number\nFile - f\nNumber - n?:").lower()

if choice2 == 'f':
    while True:
        questionsfile = input("Please enter the name of the file (without .txt):")
        try:
            # 用with语句自动管理文件资源,无需手动关闭
            with open(f"{questionsfile}.txt", 'r'):
                break  # 文件成功打开,跳出循环
        except FileNotFoundError:
            print("文件不存在,请重新输入文件名。")

二、调用计算器处理方程并输出结果

假设你已有一个calculate计算器函数,可按以下步骤处理文件内容、输出结果:

  1. 读取文件每行表达式,去除空白字符
  2. 调用计算器函数计算结果
  3. 将表达式与结果同时输出到控制台和结果文件

完整代码示例:

def calculate(expr):
    # 替换为你已有的计算器逻辑,示例用eval(注意:eval处理不可信输入有安全风险)
    try:
        return eval(expr)
    except Exception as e:
        return f"计算错误: {str(e)}"

choice2 = input("Would you like to use your own file for calculations or enter a number\nFile - f\nNumber - n?:").lower()

if choice2 == 'f':
    while True:
        questionsfile = input("Please enter the name of the file (without .txt):")
        try:
            with open(f"{questionsfile}.txt", 'r') as input_file:
                # 写入结果到文件
                with open("calculation_results.txt", 'w') as output_file:
                    for line_num, line in enumerate(input_file, 1):
                        expr = line.strip()
                        if not expr:  # 跳过空行
                            continue
                        result = calculate(expr)
                        output_content = f"第{line_num}行: {expr} = {result}"
                        print(output_content)
                        output_file.write(output_content + "\n")
                print("计算结果已保存到 calculation_results.txt")
                break
        except FileNotFoundError:
            print("文件不存在,请重新输入文件名。")

注意事项:

  • 若需处理不可信的用户输入,避免使用eval,可改用ast.literal_eval或自定义表达式解析逻辑提升安全性。
  • 代码中加入了空行处理,避免无效计算。

内容的提问来源于stack exchange,提问作者Slayer21

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 03:31:03