如何将用户输入数据写入外部文本文件?

时间:2019-11-20 19:11:40

标签: python python-3.x

我希望能够获得用户输入的测试分数并写入外部文本文件。然后让应用程序从中读取值并计算平均值。但是,我不确定如何在循环和函数中实现python语法。我试图利用我的资源来更好地了解如何执行此操作,但是在理解python如何处理外部文件时遇到了一些麻烦。另外,在这种情况下,使用append比编写更好? 当前语法:

 def testAvgCalculation():
        #Variables
        total = 0
        total_quiz = 0
        while True:
        #User Input and Variable to stop loop
            inpt = input("Enter score: ")
            if inpt.lower()== 'stop':
                break
        #Data Validation
            try:
                if int(inpt) in range(1,101):
                     total += int(inpt)
                     total_quiz += 1
                else:
                    print("Score too small or Big")
            except ValueError:
                print("Not a Number")
        return total, total_quiz


    def displayAverage(total, total_quiz):
        average = total / total_quiz

        print('The Average score is: ', format(average, '.2f'))
        print('You have entered', total_quiz, 'scores')
    #Main Function
    def main():
        total, total_quiz = testAvgCalculation()
        displayAverage(total, total_quiz)
    #Run Main Function
    main()

1 个答案:

答案 0 :(得分:0)

这很骇人,但我尝试使用已经存在的东西。我将原始函数的数据验证部分拆分为一个单独的函数。在main()中,其值counter返回到calculate_average(),该值跟踪输入了多少个值,然后counter逐行读取文件,直到def write_file(): #Variables counter = 0 file = open("Scores.txt", "w") while True: #User Input and Variable to stop loop inpt = input("Enter score: ") file.write(inpt + "\n") if inpt.lower()== 'stop': file.close() break counter += 1 return counter def calculate_average(counter): total = 0 total_quiz = counter scores = open("Scores.txt", "r") s = "" try: while counter > 0 and s != 'stop': s = int(scores.readline()) if int(s) in range(1,101): total += int(s) counter -= 1 else: print("Invalid data in file.") except ValueError: print("Invalid data found") return total, total_quiz def displayAverage(total, total_quiz): average = total / total_quiz print('The Average score is: ', format(average, '.2f')) print('You have entered', total_quiz, 'scores') #Main Function def main(): total, total_quiz = calculate_average(write_file()) displayAverage(total, total_quiz) #Run Main Function main() 变为0,这意味着它将要读取单词“ stop”(允许通过if语句中的“ and”识别EOF),执行计算并返回其值。

models/official/transformer/v2/transformer.py:143 call  *
    encoder_outputs = self.encode(inputs, attention_bias, training)

models/official/transformer/v2/transformer.py:166 encode
    embedded_inputs = self.embedding_softmax_layer(inputs)

TypeError: Cannot convert provided value to EagerTensor. Provided value: 0.0 Requested dtype: int64

注意:该文件最初是在写入模式下创建的,该模式每次都会覆盖该文件,因此您永远不需要一个新文件。如果您想保留一条记录,则可能需要更改它以追加,尽管您需要管理从旧输入中提取正确的行。

一点都不漂亮,但是应该让您了解如何实现自己的目标。