AttributeError: 'tuple' object has no attribute 'append'

我们两清 提交于 2019-12-31 04:14:10

问题


Can anyone help me with this code?

Jobs = ()
openFile = open('Jobs.txt')
x = 1
while x != 0:
    Stuff = openFile.readline(x)
    if Stuff != '':
        Jobs.append(Stuff)
    else:
        x = 0

This code throws:

AttributeError: 'tuple' object has no attribute 'append'

I'm using Python 3.6.


回答1:


In the line:

Jobs = ()

you create a tuple. A tuple is immutable and has no methods to add, remove or alter elements. You probably wanted to create a list (lists have an .append-method). To create a list use the square brackets instead of round ones:

Jobs = []

or use the list-"constructor":

Jobs = list()

However some suggestions for your code:

opening a file requires that you close it again. Otherwise Python will keep the file handle as long as it is running. To make it easier there is a context manager for this:

with open('Jobs.txt') as openFile:
    x = 1
    while x != 0:
        Stuff = openFile.readline(x)
        if Stuff != '':
            Jobs.append(Stuff)
        else:
            x = 0

As soon as the context manager finishes the file will be closed automatically, even if an exception occurs.


It's used very rarely but iter accepts two arguments. If you give it two arguments, then it will call the first each iteration and stop as soon as the second argument is encountered. That seems like a perfect fit here:

with open('Jobs.txt') as openFile:
    for Stuff in iter(openFile.readline, ''):
        Jobs.append(Stuff)

I'm not sure if that's actually working like expected because openFile.readline keeps trailing newline characters (\n) so if you want to stop at the first empty line you need for Stuff in iter(openFile.readline, '\n'). (Could also be a windows thingy on my computer, ignore this if you don't have problems!)


This can also be done in two lines, without creating the Jobs before you start the loop:

with open('Jobs.txt') as openFile:
    # you could also use "tuple" instead of "list" here.
    Jobs = list(iter(openFile.readline, ''))  

Besides iter with two arguments you could also use itertools.takewhile:

import itertools
with open('Jobs.txt') as openFile:
    Jobs = list(itertools.takewhile(lambda x: x != '', openFile))

The lambda is a bit slow, if you need it faster you could also use ''.__ne__ or bool (the latter one works because an empty string is considered False):

import itertools
with open('Jobs.txt') as openFile:
    Jobs = list(itertools.takewhile(''.__ne__, openFile))



回答2:


The Jobs object you created is a tuple, which is immutable. Therefore, you cannot "append" anything to it.

Try

Jobs = []

instead, in which you create a list object.



来源:https://stackoverflow.com/questions/41985951/attributeerror-tuple-object-has-no-attribute-append

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!