Python文本文件行缩进

时间:2019-03-18 08:05:11

标签: python python-3.x

因此,我目前正在编写此代码以获取字符串变量并将其插入文本文件中。仅此一项即可。但是,当在字符串末尾放置“ / n”之类的内容以使其换行时。那是行不通的。

studentInformation = []
studentNumber = ("Enter amount of students: ")

for i in range(o, studentNumber):
        studentInformation.append(studentNumber)
        studentID = input("Enter student ID: ")
        studentEmail = input("Enter student email: ")
        studentPhrase = studentID + "#" + studentEmail
        studentInformation[i] = studentPhrase
        print (studentPhrase)

        objectFile = open("textFile.txt", "a")

        objectFile.write('/n'.join (studentPhrase))

        objectFile.close

我的问题是文件中的输出不会缩进到下一行。输出将全部放在同一行。

1 个答案:

答案 0 :(得分:1)

  1. 使用\n代替/n

  2. 循环需要一个数字,而不是一个字符串。即

studentNumber = int(input(("Enter amount of students: ")))

  1. 您需要在print语句的末尾添加新行char。

因此:

studentInformation = []
studentNumber = int(input(("Enter amount of students: ")))

for i in range(0, studentNumber):
        studentInformation.append(studentNumber)
        studentID = input("Enter student ID: ")
        studentEmail = input("Enter student email: ")
        studentPhrase = studentID + "#" + studentEmail
        studentInformation[i] = studentPhrase
        print (studentPhrase)
        objectFile = open("list.txt", "a")
        objectFile.write(studentPhrase + '\n')
        objectFile.close

输出

Enter amount of students: 3
Enter student ID: 123
Enter student email: em@gmail.com
123#em@gmail.com
Enter student ID: 2
Enter student email: abc@fgh.com
2#abc@fgh.com
Enter student ID: 1
Enter student email: olp@olp.com
1#olp@olp.com

输出(来自文件)

123#em@gmail.com
2#abc@fgh.com
1#olp@olp.com