首页 > 解决方案 > 将文本打印到文本文件中的程序

问题描述

我需要创建一个程序来接收用户的身份证号码来创建学校注册系统,然后将信息导出到 .txt 文件中。我的问题是我没有将输入的每个 ID 号写入新行,我需要帮助。

我已将每个 id 放入一个列表中,然后将它们全部连接到一个字符串中。现在我需要在单独的行上打印字符串中的每个 ID 号。请告诉我在哪里插入“\n”,以便在 txt 文件的新行上打印。

# we first define the name of the file and set it to write mode
to_file = open("RegForm.txt" , "w")

# list variable for storing the received i.d. numbers
id_numbers = []

# asking the user to enter the number of students that will write the exam
num = int(input("Please enter the number of students that will sit for the exam: "))



# creating a loop that iterates over every student who is writing the exam
# we then append the list of id numbers with each new input we receive

for toFile in range(0, num):
    id_numbers.append(input("Enter your ID Number: " ))

# we create the variable string_of_nums which is joining the list into a single string
string_of_nums = " ".join(id_numbers)

# writing the id numbers onto the text file
to_file.write(string_of_nums)

# closing the file
to_file.close()

我需要它在单独的行上打印每个 ID 号

标签: python

解决方案


string_of_nums = "\n".join(id_numbers)


推荐阅读