【问题标题】:Python - unable to save all the inputs from the user into a text filePython - 无法将用户的所有输入保存到文本文件中
【发布时间】:2020-05-01 15:44:28
【问题描述】:

我有一个循环运行次数与用户输入一样多,但我无法将用户的所有输入保存到文本文件中

       ofile = open('RegForm.txt', 'a') 
  1. 用户输入循环运行的次数

       loops = int(input("How many students will be registering for the course? "))
    
       inputs = []
       for x in range(loops):
    
  2. 循环将根据用户初始输入运行,请求用户输入附加信息 保存在一个 txt 文件中,但它只保存最后一个输入。 inputs.append(input("请输入学生编号:"))

       ofile.write(inputs)
       ofile.close()
    

【问题讨论】:

    标签: python loops file text append


    【解决方案1】:

    目标是将完整列表存储到文件中吗?在这种情况下,您不需要在 for 循环期间将列表中的每个项目附加到文件中。

    看下面的代码:

    loops = int(input("How many students will be registering for the course? "))
    
    inputs = []
    
    for x in range(loops):
        inputs.append(input("Enter the students number: "))
    
    print(inputs)
    
    with open('RegForm.txt', 'w') as ofile:
    
        for item in inputs:
    
            ofile.write("%i\n" % item)
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-15
      • 2015-11-02
      • 1970-01-01
      相关资源
      最近更新 更多