generator no iter - how do I call it from another function
Sayth Renshaw
flebber.crue at gmail.com
Sat Oct 1 04:52:07 EDT 2016
Evening
My file list handler I have created a generator.
Before I created it as a generator I was able to use iter on my lxml root objects, now I cannot iter.
± |master U:2 ?:1 ✗| → python3 race.py data/ -e *.xml
Traceback (most recent call last):
File "race.py", line 83, in <module>
dataAttr(rootObs)
File "race.py", line 61, in dataAttr
for meet in roots.iter("meeting"):
AttributeError: 'generator' object has no attribute 'iter'
How do I now pull the next iterations through from the other function?
from lxml import etree
import csv
import re
import argparse
import os
parser = argparse.ArgumentParser()
parser.add_argument("path", type=str, nargs="+")
parser.add_argument(
'-e', '--extension', default='', help='File extension to filter by.')
# >python race.py XML_examples/ -e .xml
args = parser.parse_args()
name_pattern = "*" + args.extension
my_dir = args.path[0]
for dir_path, subdir_list, file_list in os.walk(my_dir):
for name_pattern in file_list:
full_path = os.path.join(dir_path, name_pattern)
def return_files(file_list):
"""
Take a list of files and return file when called.
Calling function to supply attributes
"""
for filename in sorted(file_list):
with open(dir_path + filename) as fd:
tree = etree.parse(fd)
root = tree.getroot()
yield root
def clean(attr):
"""
Split list into lists of 5 elements.
if list is less than 5 in length then a 0
is appended and the list returned
"""
p = re.compile('\d+')
myList = p.findall(attr)
if len(myList) < 5:
myList.append('0')
return myList[0], myList[1], myList[2], myList[3], myList[4]
def dataAttr(roots):
"""Get the root object and iter items."""
with open("output/first2.csv", 'w', newline='') as csvf:
race_writer = csv.writer(csvf, delimiter=',')
for meet in roots.iter("meeting"):
print(meet)
for race in roots.iter("race"):
for nom in roots.iter("nomination"):
meetattr = meet.attrib
raceattr = race.attrib
nomattr = nom.attrib
if nomattr['number'] != '0':
firsts = clean(nomattr['firstup'])
race_writer.writerow(
[meetattr['id'], meetattr['date'],
meetattr['venue'], raceattr['id'],
raceattr['number'], raceattr['distance'],
nomattr['id'], nomattr['barrier'],
nomattr['weight'], nomattr['rating'],
nomattr['description'], nomattr['dob'],
nomattr['age'], nomattr['decimalmargin'],
nomattr['saddlecloth'], nomattr['sex'],
firsts[4]])
rootObs = return_files(file_list)
dataAttr(rootObs)
More information about the Python-list
mailing list