问题
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(',')
回答1:
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)
回答2:
ClassFile
is an object of type _io.TextIOWrapper
which does not has any attribute append
. You are mistaking it to be an object of type List. It seems in place of ClassFile.append(filelines) you want something like filelines.append(line)
.
If you want to write something into a file, open it in write or append mode (depending on your need) and write into it the string you want.
来源:https://stackoverflow.com/questions/30593981/python-attributeerror-io-textiowrapper-object-has-no-attribute-append