Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a homework assignment for a Python class and am running into an error that I don't understand. Running Python IDLE v3.2.2 on Windows 7.

Below is where the problem is happening:

#local variables
number=0
item=''
cost=''

#prompt user how many entries
number=int(input('\nHow many items to add?: '))

#open file
openfile=('test.txt','w')

#starts for loop to write new lines
for count in range(1,number+1):
    print('\nFor item #',count,'.',sep='')
    item=input('Name:  ')
    cost=float(input('Cost: $'))

    #write to file
    openfile.write(item+'\n')
    openfile.write(cost+'\n')

#Display message and closes file
print('Records written to test.txt.',sep='')
openfile.close

This is the error that I am getting:

Traceback (most recent call last): File "I:\Cent 110\test.py", line 19, in openfile.write(item+'\n')
AttributeError: 'tuple' object has no attribute 'write'

like image 911
dhc Avatar asked Apr 17 '12 10:04

dhc


People also ask

How do you fix tuple object has no attribute?

The Python "AttributeError: 'tuple' object has no attribute" occurs when we access an attribute that doesn't exist on a tuple. To solve the error, use a list instead of a tuple to access a list method or correct the assignment.

What does object has no attribute mean in Python?

It's simply because there is no attribute with the name you called, for that Object. This means that you got the error when the "module" does not contain the method you are calling.

Is a tuple an object?

A tuple is a collection of objects which ordered and immutable. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.

How do you define a tuple?

Tuple. Tuples are used to store multiple items in a single variable. Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage. A tuple is a collection which is ordered and unchangeable.


1 Answers

You're missing the open.

openfile = open('test.txt','w')

And at the end there are missing parens when you try to close the file

openfile.close()

Edit: I just saw another problem.

openfile.write(str(cost)+'\n')
like image 85
Matthias Avatar answered Nov 09 '22 05:11

Matthias