Python-AttributeError:"_ io.TextIOWrapper"对象没有属性"append" [英] Python - AttributeError: '_io.TextIOWrapper' object has no attribute 'append'

查看:888
本文介绍了Python-AttributeError:"_ io.TextIOWrapper"对象没有属性"append"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到一个错误

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

ClassFile.append(filelines) AttributeError: '_io.TextIOWrapper' object has no attribute '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()调用 移出了循环.

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)

这篇关于Python-AttributeError:"_ io.TextIOWrapper"对象没有属性"append"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆