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'
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.
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.
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.
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.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With