ValueError: I/O operation on closed file Why this happens? Automate boring stuff with python book

ValueError: I/O operation on closed file Why this happens? Automate boring stuff with python book

我是新手 正在看书 Automate Boring Stuff with python

本章的第一个项目展示了如何使用Random、write、read、close和open

制作Random Quiz generator

This is my code

#! python3
# randomQuizGenerator.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', 'Alaska': 'Juneau', 'Arizona': 'Phoenix',
   'Arkansas': 'Little Rock', 'California': 'Sacramento', 'Colorado': 'Denver',
   'Connecticut': 'Hartford', 'Delaware': 'Dover', 'Florida': 'Tallahassee',
   'Georgia': 'Atlanta', 'Hawaii': 'Honolulu', 'Idaho': 'Boise', 'Illinois':
   'Springfield', 'Indiana': 'Indianapolis', 'Iowa': 'Des Moines', 'Kansas':
   'Topeka', 'Kentucky': 'Frankfort', 'Louisiana': 'Baton Rouge', 'Maine':
   'Augusta', 'Maryland': 'Annapolis', 'Massachusetts': 'Boston', 'Michigan':
   'Lansing', 'Minnesota': 'Saint Paul', 'Mississippi': 'Jackson', 'Missouri':
   'Jefferson City', 'Montana': 'Helena', 'Nebraska': 'Lincoln', 'Nevada':
   'Carson City', 'New Hampshire': 'Concord', 'New Jersey': 'Trenton', 
   'NewMexico': 'Santa Fe', 'New York': 'Albany',
   'North Carolina': 'Raleigh', 'North Dakota': 'Bismarck', 
   'Ohio': 'Columbus', 'Oklahoma': 'Oklahoma City',
   'Oregon': 'Salem', 'Pennsylvania': 'Harrisburg', 'Rhode Island': 'Providence',
   'South Carolina': 'Columbia', 'South Dakota': 'Pierre', 'Tennessee':
   'Nashville', 'Texas': 'Austin', 'Utah': 'Salt Lake City', 'Vermont':
   'Montpelier', 'Virginia': 'Richmond', 'Washington': 'Olympia', 
   'WestVirginia': 'Charleston', 'Wisconsin': 'Madison', 'Wyoming': 'Cheyenne'}

   # Generate 35 quiz files.
for quizNum in range(35):
  # Create the quiz and answer key files.
  quizFile = open(f'capitalsquiz{quizNum + 1}.txt', 'w')
  answerKeyFile = open(f'capitalsquiz_answers{quizNum + 1}.txt', 'w')
     # Write out the header for the quiz.
  quizFile.write('Name:\n\nDate:\n\nPeriod:\n\n')
  quizFile.write((' ' * 20) + f'State Capitals Quiz (Form{quizNum + 1})')
  quizFile.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 questionNum in range(50):

         # Get right and wrong answers.
      correctAnswer = capitals[states[questionNum]]
      wrongAnswers = list(capitals.values())
      del wrongAnswers[wrongAnswers.index(correctAnswer)]
      wrongAnswers = random.sample(wrongAnswers, 3)
      answerOptions = wrongAnswers + [correctAnswer]
      random.shuffle(answerOptions)

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

      # Write the answer key to a file.
      answerKeyFile.write(f"{questionNum + 1}.{'ABCD'[answerOptions.index(correctAnswer)]}")
      quizFile.close()
      answerKeyFile.close()

Here is what the program does:

  1. 创建 35 个不同的测验

  2. 为每个测验创建 50 个多项选择题,顺序随机 为每个问题提供正确答案和三个随机错误答案,顺序随机

  3. 将测验写入 35 个文本文件

  4. 将答案写入 35 个文本文件

This means the code will need to do the following:

  1. 将州及其首都存储在字典中
  2. 为测验和答案文本文件调用 open()、write() 和 close()
  3. 使用random.shuffle()随机化问题和多项选择的顺序

但是这段代码给出了一个错误

ValueError: I/O operation on closed file.

Traceback (most recent call last): File "/home/hp/Documents/Developement/pob/ch9/randomQuizGenarotor.py", line 50, in quizFile.write(f'{questionNum + 1}. What is the capital of{states[questionNum]}?\n') ValueError: I/O operation on closed file.

当我删除代码时它会起作用

      quizFile.close()
      answerKeyFile.close()

但是有一些问题

我想用它

看起来 close() 函数在 for 循环中,因此在第一次迭代后它将关闭文件。将 close() 函数移到 for

之外