将文本打印到文本文件中的程序

时间:2019-05-11 10:23:28

标签: python

我需要创建一个程序,该程序使用用户的i.d编号来创建学校注册系统,然后将信息导出到.txt文件中。我的问题是我无法写每个i.d.数字输入到新行中,我需要帮助。

我把每个i.d.进入列表,然后将它们全部加入一个字符串中。现在我需要打印每个身份证单独的字符串中的数字。请告诉我在何处插入“ \ 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。单独行号

3 个答案:

答案 0 :(得分:1)

string_of_nums = "\n".join(id_numbers)

答案 1 :(得分:1)

您要在每行末尾添加换行符('\n'),因此在将各行连接在一起时,请使用换行符作为连接字符串。

string_of_nums = "\n".join(id_numbers)

答案 2 :(得分:0)

您当前的string_of_nums用空格分隔每个学生ID。

string_of_nums = " ".join(id_numbers)

join()的定义和用法

  

join()方法以可迭代方式获取所有项目,并将它们连接为一个字符串。   必须将字符串指定为分隔符。

因此,“”中的内容将成为您的字符串分隔符。

因此,要使用换行符分隔每个学生,我们必须插入 \ n

string_of_nums = "\n".join(id_numbers)