Python Forum

Full Version: Tuple no attribute error
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Linux Mint 18.2 Python 3.5. Am old time BASIC person.
Help. Have no understanding how to deal with this.
An example please.


 #!/usr/bin/python3
 #
 with open( 'expenses-18', 'r') as yrs_file:
     for line in enumerate(yrs_file):
         (pdate,catg,amt,howp) = line.split(',')
         pdate = str(pdate)
         length = len(pdate)
         catg = int(catg)
         amt = float(amt)
         howp = int(howp)
# Will do stuff here. 
         print pdate, catg, amt, howp

Traceback (most recent call last):
  File "try-me.py", line 5, in <module>
    (pdate,catg,amt,howp) = line.split(',')
AttributeError: 'tuple' object has no attribute 'split'
The problem is enumerate. Enumerate returns a tuple of an index of the item and the item. Since you don't seem to be using an index for the lines in the loop, I would just loop over yrs_file, not enumerate(yrs_file).
enumerate() returns a tuple containing two items. First is an index (starting with 0) and second is an item from the iterable you enumerated.

for line in enumerate(yrs_file):
Here line is a tuple (index, item), so you can't use split on it, which is a method of string type.
You could instead unpack the tuple into two variables like this:
for index, line in enumerate(yrs_file):
Then line will be a string which you can split.
You could also access only the second element of the tuple - the string you want to split:
for line in enumerate(yrs_file):
    (pdate,catg,amt,howp) = line[1].split(',')
But in any case, I don't really see why you would need enumerate() in your code at all.
(Oct-06-2018, 02:51 PM)oldcity Wrote: [ -> ]Linux Mint 18.2 Python 3.5.
You can remove enumerate() as mention bye @j.crater.
I guess you have file that has lines with 4 values.
>>> line = 'a, 1, 2, 3'
>>> (pdate,catg,amt,howp) = line.split(',')
>>> pdate
'a'
>>> catg
' 1'
Quote:# Will do stuff here.
print pdate, catg, amt, howp
You are not using Python 3.5,this will give SyntaxError.
Have to use python3 to use Python 3.5 on mint 18.
print() is a function python 3.
print(pdate, catg, amt, howp)