试图制作flashcard程序,在读取文本文件时收到错误

时间:2017-01-19 05:48:58

标签: python-3.x

首先,我必须说我已经在这个网站上学到了很多东西,经过几个小时的磨头,我带着谦卑的心情向你求助。简而言之,我正在尝试制作闪卡程序。前提很简单:系统会提示用户提问和四个答案。用户选择答案,并告知他们是否选择对错,以及答案的解释。问题,答案,正确答案和解释都在一个文本文件中,该文件在程序中以“读取”格式打开,并从指定目录中随机选择,因为每个文本文件只有一个问题/答案集。

现在,我终于明白程序似乎会正确打开文件(我想)。尝试从文件中读取行时会发生有趣的部分。我一直收到错误

  
    

追踪(最近一次调用最后一次):文件“test2.py”,第69行,

         

         

main()文件“test2.py”,第55行,在主

中          

问题,答案,正确,解释= next_block(trivia_file)文件“test2.py”,第35行,在next_block中

         

category = next_line(the_file)文件“test2.py”,第29行,在next_line中

         

line = the_file.readline()AttributeError:'str'对象没有属性'readline'

  

运行程序时。我试过操纵代码,没有任何工作。代码如下所示。现在,我仍然是一个初学者,所以请保持温和,但也要知道任何建议和智慧将得到最大的尊重和赞赏。换句话说,请帮忙。此外,如果我可以使用另一种更明智的方法,我愿意接受建议。如果你有任何问题,我会回答你的问题。再次感谢你。

   import os
import random
import sys

#select and open random file in specified folder
def getRandomFile(path):
  """
  Returns a random filename, chosen among the files of the given path.
  """
  files = os.listdir(path)
  index = random.randrange(0, len(files))
  return files[index]


#open file of random name chosen
def openRandomFile(file_name, mode):
    """Open a file."""
    try:
        the_file = open(file_name, mode)
    except IOError as e:
        print("Unable to open the file", file_name, "Ending program.\n", e)
        input("\n\nPress the enter key to exit.")
        sys.exit()
    else:
        return the_file

def next_line(the_file):
    """Return next line from the trivia file, formatted."""
    line = the_file.readline()
    line = line.replace("/", "\n")
    return line

def next_block(the_file):
    """Return the next block of data from the trivia file."""
    category = next_line(the_file)

    question = next_line(the_file)

    answers = []
    for i in range(4):
        answers.append(next_line(the_file))

    correct = next_line(the_file)
    if correct:
        correct = correct[0]

    explanation = next_line(the_file)

    return category, question, answers, correct, explanation

def main():
  #choose file to open
  trivia_file = getRandomFile("/home.../trivia")
  run_file = openRandomFile("/home.../trivia/" + trivia_file, "r")
  question, answers, correct, explanation = next_block(trivia_file)
  #ask a question
  for i in range(4):
    print("\t", i + 1, "-", answers[i])
    #get answer
    answer = input("What's your answer?:")
      #check answer
    if answer == correct:
      print("\nRight!", end=" ")
    else:
      print("\nWrong.", end=" ")
    print("Explanation\n", explanation)
    input("Press enter to continue.")  

main()
input("\n\nPress the enter key to exit.")

0 个答案:

没有答案