Python - AttributeError: '_io.TextIOWrapper' 对象没有属性 'append'

Klo*_*ano 7 python attributeerror

我收到一个错误

ClassFile.append(filelines) AttributeError: '_io.TextIOWrapper' object has no attribute 'append'

在尝试写入文件时。这是关于写一个关于学生分数的文件,他们的名字,姓氏,班级名(只需输入班级Class 1)一个分数和他们的分数的分数。只有他们的最后 3 个分数才会保存在文件中。我不明白这是什么意思。

这是代码

score=3
counter=0

name=input('Name:')
surname=input('Last Name:')
Class=input('Class Name:')

filelines=[]

Class=open(Class+'.txt','r')
line=Class.readline()
while line!='':
    Class.append(filelines)
    Class.close()

linecount=len(filelines)
for i in range(0,linecount):
    data=filelines[i].split(',')
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 7

你把你的附加代码搞混了;该append()方法在filelines对象上:

ClassFile=open(CN+'.txt','r')
line=ClassFile.readline()
while line!='':
    filelines.append(line)
ClassFile.close()
Run Code Online (Sandbox Code Playgroud)

请注意,我还将close()调用移出循环。

你不需要在while那里使用循环;如果你想要一个包含所有行的列表,你可以简单地做:

ClassFile=open(CN+'.txt','r')
filelines = list(ClassFile)
ClassFile.close()
Run Code Online (Sandbox Code Playgroud)

要处理文件关闭,请使用文件对象作为上下文管理器:

with open(CN + '.txt', 'r') as openfile:
    filelines = list(openfile)
Run Code Online (Sandbox Code Playgroud)