将用户输入写入.txt文件(Python 3)

时间:2018-03-23 14:49:39

标签: python python-3.x

我一直在研究这个学生成绩计算器几个星期,现在被告知我需要写入.txt文件的名称/等级,我已经使用了这个项目的用户输入,我现在正在努力收集数据并将其存储到文件中。希望有人能让我走上正确的道路,这是我的代码......

    print("---------------------------------------------------------------")
    Number_Of_Numbers = int(input("How many students do you want to add? "))
    print("---------------------------------------------------------------")
    Numbers_To_Be_Added = []
    for i in range(Number_Of_Numbers):
        print ('Please enter your name')
        str1 = (input())  
        print ('Please enter your grade')
        Number = float(input())
        print("---------------------------------------------------------------")
        while Number <0 or Number >= 101:  
           print("Error")
           print ('Please enter your grade')
           Number = float(input())
           print("---------------------------------------------------------------")
           if Number >= 0 and Number <= 100:
              break
        Numbers_To_Be_Added.append(Number)
        total = sum(Numbers_To_Be_Added)
        if i == Numbers_To_Be_Added:
          break
        average = (total /Number_Of_Numbers)
    print ("The Average is: ","{0:.3f}".format(average))
    print("---------------------------------------------------------------")
    print("Goodbye!")
    print("---------------------------------------------------------------")

    with open('Results.txt','w') as f:
        f.write('')

如您所见,我有写入文件的功能,我不知道如何从用户输入中收集数据。

1 个答案:

答案 0 :(得分:-1)

有一些方法可以在文件中写入数据

要重写.txt文件:

file = open("any_file_name.txt", "w")
file.write("info")

要附加到.txt文件:

file = open("any_file_name.txt", "a")
file.write("info")

当然,在输入数据后,您需要将其接收回来

要阅读.txt文件,请添加“#”和“\ n”之类的分隔符:

file = open("any_file_name.txt", "r")
all_the_data = []
for line in file:
    one_piece_of_data = line.split("#")[0]
    all_the_data.append(one_piece_of_data)
# now all the data is in the variable!