Python - AttributeError: '_io.TextIOWrapper' 对象没有属性 'append'
我收到一个错误
ClassFile.append(filelines)AttributeError: '_io.TextIOWrapper' 对象没有属性 'append'
尝试写入文件时.这是关于写一个关于学生分数的文件,他们的名字,姓氏,班级名称(只需输入班级为Class 1
)一个分数和他们的分数的分数.只有他们的最后 3 个分数才会保存在文件中.我不明白这是什么意思.
while trying to write a file. It is about writing a file about pupil's scores, their name, lastname, classname (Just enter class as Class 1
)a scorecount of how many scores and their scores. Only their last 3 scores are to be kept in the file. I don't understand what this means.
这是代码
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(',')
你把追加代码搞混了;append()
方法位于 filelines
对象上:
You got your append code all mixed up; the append()
method is on the filelines
object:
ClassFile=open(CN+'.txt','r')
line=ClassFile.readline()
while line!='':
filelines.append(line)
ClassFile.close()
请注意,我还移动了循环的 close()
调用 out.
Note that I also moved the close()
call out of the loop.
你不需要在那里使用 while
循环;如果你想要一个包含所有行的列表,你可以简单地做:
You don't need to use a while
loop there; if you want a list with all the lines, you can simply do:
ClassFile=open(CN+'.txt','r')
filelines = list(ClassFile)
ClassFile.close()
要处理文件关闭,请使用文件对象作为上下文管理器:
To handle file closing, use the file object as a context manager:
with open(CN + '.txt', 'r') as openfile:
filelines = list(openfile)