Python - 无法将用户的所有输入保存到文本文件中

标签 python loops file text append

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

       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. 循环将根据用户初始输入运行,请求用户输入 append 信息 保存在txt文件中,但它只保存最后一次输入。 input.append(input("请输入学号:"))

       ofile.write(inputs)
       ofile.close()
    

最佳答案

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

看下面的代码:

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)

关于Python - 无法将用户的所有输入保存到文本文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59741855/

相关文章:

python - 如何使用 Selenium 抓取多个 URL 的内容? Python

c# - 从 dotnet 程序集检索资源

python - 将两个查询集组合成一个模板标签

python - Processing.py草图错误: unclosed paren/quote mark

c - 使用递归乘以幂

java - 如何在 JSTL/JSP 的循环中连接字符串?

javascript - 如何将多个文件选择放入数组中然后输出到 HTML

C 字符串字符串比较总是导致 false

javascript - Python 与 javascript 列表

python - 如何替换非重读元音?