简体   繁体   中英

Mysterious new line character when writing to a text file

def addCourse(studentId,courseAdd): #Registers the student's id to a class they input
    infile = open('student_database.txt','r')
    data = infile.readlines()
    outfile = open('student_database.txt','w')
    for line in data:
        if studentId+" " in line:
            line = line+" "+courseAdd
        outfile.write(line) #We rewrite all lines to the file whether they where modified or not
    infile.close()
    outfile.close()

This is a function that should add something like "course4" to the end of the first line of a text file. It should look something like this if the studentId in this instance is studentID

studentID course course2 course3 course4
studentID2 course course2 course3

however after the code runs it ends up looking like this

studentID course course2 course3
 course4studentID2 course course2 course3

Why is course4 added to the wrong line?

Each line of data you read from the file already has a newline character at the end of it. If you append something to the line, it will go after the newline, and therefore appear on the next line.

Source

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM