Tuple no attribute error - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Tuple no attribute error (/thread-13250.html) |
Tuple no attribute error - oldcity - Oct-06-2018 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' RE: Tuple no attribute error - ichabod801 - Oct-06-2018 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). RE: Tuple no attribute error - j.crater - Oct-06-2018 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. RE: Tuple no attribute error - snippsat - Oct-06-2018 (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.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) |