Search code examples
pythonfileattributesgenerator

AttributeError: 'generator' object has no attribute 'isdigit'


I'm trying to go through this file that I've created and only extract the ages of the people in the file. then take the average of the ages and print it out. I'm trying to iterate through the lines in the file and it says that the generator object has no attribute. I'm using python 3 and I commented out some code I was using before so I don't have to worry about it. I don't know if I should use the commented code either but I'm just scared of losing all the ideas I've gotten this far. How do I get those ages in my loop if I can't iterate through?

f = open('myfile.txt','w')
f.write('Name, Age, Gender, Profession\n')
f.write('Harry, 23, Male, Software Engineer\n')
f.write('Sam, 25, Male, Lawyer\n')
f.write('Lisa, 29, Female, Computer Scientist\n')
f.write('Mary, 22, Female, Doctor\n')
f.close()
# print(readFile.read())
# readFile = open("myfile.txt")

with open('myfile.txt', 'r') as file:


    for line in file:
        values = (line.split(', ') for line in file)
        if values.isdigit[1] == True:
            numbers = 0
            numbers += values

    average = numbers % 4
    print(average)


Solution

  • Try:

    f = open('myfile.txt','w')
    f.write('Name, Age, Gender, Profession\n')
    f.write('Harry, 23, Male, Software Engineer\n')
    f.write('Sam, 25, Male, Lawyer\n')
    f.write('Lisa, 29, Female, Computer Scientist\n')
    f.write('Mary, 22, Female, Doctor\n')
    f.close()
    
    with open('myfile.txt', 'r') as file:
        numbers = 0
        for line in file:
            values = line.split(', ')
            if values[1].isdigit() == True:
                numbers += int(values[1])
    
        average = numbers / 4
        print(average) # 24.75
    

    There are several points that can be improved:

    1. values = (line.split(', ') for line in file) assignes a generator (mind the seemingly innocent parenthesis) to values, and a generator does not have isdigit. You are already using a for loop, so you don't need a generator (actually you shouldn't).

    2. In the corrected code, values now is a list of strings. So you need to use values[1] to access an item of the list, and then apply isdigit.

    3. You are resetting numbers in each iteration. Initiate the variable before the loop.

    4. values[1] is a string, so in order to add this to numbers, you need int.

    5. % is the modulus operator. Use / for (real) division.

    6. Using a hard-coded number (in this case, dividing something by a specific number 4) is not a best option. You might want an alternative way to get the number of records.