Search code examples
pythonattributeerror

Python - AttributeError: '_io.TextIOWrapper' object has no attribute 'append'


I receive an error

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

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.

Here is the code

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(',')

Solution

  • 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()
    

    Note that I also moved the close() call out of the loop.

    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)