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

Python自定义函数写入txt文件触发write()参数TypeError报错

问题说明

开发Python自动化测验生成工具时,用于写入多选题内容的create_multiple_choice函数运行失败,抛出如下报错:

dit_quiz_file.write(multiple_choice_question, "a")
TypeError: write() takes exactly one argument (2 given)

对应出错代码片段:

def create_multiple_choice():
    global edit_quiz_file
    multiple_choice_question = input("What would you like the question to be?")
    print("write the multiple choice options below\n")
    multiple_choice1 = input("What is the first option?")
    multiple_choice2 = input("What is the second option?")
    multiple_choice3 = input("What is the third option?")
    multiple_choice4 = input("What is the fourth option?")
    
    edit_quiz_file = open("mathquiz.txt", "a")
    edit_quiz_file.write(multiple_choice_question, "a")
错误原因
  • 文件对象的write()方法仅支持传入1个参数(即要写入的字符串内容),你误将open()函数使用的追加模式参数"a"传给了write(),参数数量不匹配触发报错。
  • 现有逻辑只收集了4个选项的用户输入,没有编写选项写入文件的对应代码,就算修复参数错误,最终输出的txt文件也只会保存题干,不会显示多选选项。
  • 直接调用open()打开文件后没有执行关闭操作,容易出现文件资源泄漏、内容写入不全的问题。
  • 不必要的global全局变量声明会增加代码调试难度,文件操作不需要依赖全局变量。
修复后可运行代码
def create_multiple_choice():
    multiple_choice_question = input("What would you like the question to be?")
    print("write the multiple choice options below\n")
    multiple_choice1 = input("What is the first option?")
    multiple_choice2 = input("What is the second option?")
    multiple_choice3 = input("What is the third option?")
    multiple_choice4 = input("What is the fourth option?")
    
    # with上下文管理器会在写入完成后自动关闭文件,无需手动调用close()
    with open("mathquiz.txt", "a", encoding="utf-8") as edit_quiz_file:
        # 写入题干后加换行
        edit_quiz_file.write(f"{multiple_choice_question}\n")
        # 按标准多选题格式写入选项,加A/B/C/D前缀
        edit_quiz_file.write(f"A. {multiple_choice1}\n")
        edit_quiz_file.write(f"B. {multiple_choice2}\n")
        edit_quiz_file.write(f"C. {multiple_choice3}\n")
        edit_quiz_file.write(f"D. {multiple_choice4}\n")
        # 题目末尾加空行,和后续题目分隔
        edit_quiz_file.write("\n")
修改点说明
  • 移除write()方法中多余的"a"参数,追加写入模式仅需在open()打开文件时指定即可。
  • 补全选项写入逻辑,添加选项前缀和换行符,避免所有内容挤在同一行,输出格式更规范。
  • 用with语句替代手动open()/close()流程,自动管理文件资源,避免写入异常。
  • 删除冗余的全局变量声明,降低代码耦合度。
  • 打开文件时指定encoding="utf-8",避免中文内容写入时出现乱码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 23:06:22