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)
CodePudding user response:
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 issues:
values = (line.split(', ') for line in file)assignes a generator tovalues, and a generator does not haveisdigit. You are already using aforloop, so you don't need a generator (actually you shouldn't).In the corrected code,
valuesnow is a list of strings. So you need to usevalues[1]to access an item of the list, and then applyisdigit.You are resetting
numbersin each iteration. Initiate the variable before the loop.values[1]is a string, so in order to add this tonumbers, you needint.%is the modulus operator. Use/for division.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.
