alkalinear
alkalinear

Reputation: 1

Python, why is my loop writing a blank space to the end of the list from text file

correctAnswers = ['A','C','A','A','D','B','C','A','C','B','A','D','C','A','D','C','B','B','D','A']

studentAnswers = []
correctList = []
file = open('forchapter7.txt','r')

student = file.readline()
student = student.rstrip('\n')
studentAnswers.append(student)

while student != '':

    student = file.readline()
    student = student.rstrip('\n')
    studentAnswers.append(student)

print(studentAnswers)
print(correctAnswers)


file.close()    

#displays this

['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', '']
['A', 'C', 'A', 'A', 'D', 'B', 'C', 'A', 'C', 'B', 'A', 'D', 'C', 'A', 'D', 'C', 'B', 'B', 'D', 'A']

my text file is a plain .txt file with the letters A-T going down and no space or new line after T, why is my loop writing the blank space?

Upvotes: 0

Views: 484

Answers (1)

bj0
bj0

Reputation: 8213

When you read your final line, student == 'T', so the loop repeats itself. When you try to file.readline() after you have finished reading the entire file, it returns '' because there is nothing else to read. You are then adding this to your list.

Just add a check for empty string before adding to the list:

if student:
   studentAnswers.append(student)

EDIT: An alternative you could use is to read all the lines with file.readlines() and iterate over the list. This will not run the loop an extra time:

for student in file.readlines():
    studentAnswers.append(student.rstrip('\n')

You can even use list comprehension this way:

studentAnswers = [student.rstrip('\n') for student in file.readlines()]

Note, however, that if the file does have an empty line these last two methods will need checks to prevent them from adding an empty entry to the list.

Upvotes: 1

Related Questions