Python程序说文件已关闭但应打开

问题描述 投票:0回答:1

我有这个Python程序:

#! python3
# random_quiz_generator.py - Creates quizzes with questions and answers in random order, along with the answer key.

import random

# The quiz data. Keys are states and values are their capitals
capitals = {'Alabama': 'Montgomery',
            .......
            'Wyoming': 'Cheyenne'
            }

# Generate 35 quiz files
for quiz_num in range(35):
    # create the quiz and answer key files
    quiz_file = open(f'capitalsquiz{quiz_num + 1}.txt', 'w')
    answer_key_file = open(f'capitalsquiz_answers{quiz_num +1}.txt', 'w')

    # write out the header for the quiz
    quiz_file.write('Name:\n\nDate:\n\nPeriod:\n\n')
    quiz_file.write((' ' * 20) + f'State Capitals Quiz (Form{quiz_num +1})')
    quiz_file.write('\n\n')

    # shuffle the order of the states
    states = list(capitals.keys())
    random.shuffle(states)

    # loop through all 50 states, making a question for each
    for question_num in range(50):
        # get right and wrong answers
        correct_answer = capitals[states[quiz_num]]
        wrong_answers = list(capitals.values())
        del wrong_answers[wrong_answers.index(correct_answer)]
        wrong_answers = random.sample(wrong_answers, 3)
        answer_options = wrong_answers + [correct_answer]
        random.shuffle(answer_options)

        # write the question and answer options to the quiz file
        quiz_file.write(f'{question_num + 1}. What is the capital of {states[question_num]}?\n')
        for i in range(4):
            quiz_file.write(f"  {'ABCD'[i]}. {answer_options[i]}\n")
            quiz_file.write('\n')

        # write the answer key to a file
        answer_key_file.write(f"{question_num + 1}. {'ABCD'[answer_options.index(correct_answer)]}")
        quiz_file.close()
        answer_key_file.close()

我收到此错误:

Traceback (most recent call last):
  File "/RandomQuizGenerator/random_quiz_generator.py", line 85, in <module>
    quiz_file.write(f'{question_num + 1}. What is the capital of {states[question_num]}?\n')
ValueError: I/O operation on closed file.

我不明白为什么会关闭此文件。在quiz_file = open(f'capitalsquiz{quiz_num + 1}.txt', 'w')之后,直到我关闭它才应该保持打开状态吗?

python python-3.x ioerror
1个回答
1
投票

问题是您在循环之前打开了文件,并在最后一行的每次迭代中将其关闭,因此对于for question_num in range(50)的第二次迭代,它将被关闭。

© www.soinside.com 2019 - 2024. All rights reserved.