简体   繁体   English

Python,为什么我的循环将文本文件中的空白写入列表的末尾

[英]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 AT going down and no space or new line after T, why is my loop writing the blank space? 我的文本文件是一个普通的.txt文件,其字母AT向下,在T后面没有空格或换行,为什么我的循环写空格?

When you read your final line, student == 'T' , so the loop repeats itself. 当您阅读最后一行时, student == 'T' ,因此循环会重复。 When you try to file.readline() after you have finished reading the entire file, it returns '' because there is nothing else to read. 读取完整个文件后,尝试使用file.readline() ,它将返回''因为没有其他要读取的内容。 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. 编辑:您可以使用的替代方法是使用file.readlines()读取所有行并遍历列表。 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. 但是请注意,如果文件确实有一个空行,则需要检查这后两种方法,以防止它们将空条目添加到列表中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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