I'm trying to find a file then parse it, but I'm having trouble calling it in my second part of my script:
from xml.dom import minidom
import sys
import os, fnmatch
def find_files(directory, pattern):
for root, dirs, files in os.walk(directory):
for basename in files:
if fnmatch.fnmatch(basename, pattern):
filename = os.path.join(root, basename)
yield filename
for filename in find_files('c:/Python27','*file.xml'):
print ('Found file.xml:', filename)
def xmlparse():
xmldoc = minidom.parse(filename)
itemlist = xmldoc.getElementsByTagName('Game')
for item in itemlist:
year = item.getElementsByTagName('Year')
for s in year:
print item.attributes['name'].value, s.attributes['value'].value
You might want to change your xmlparse
function to take a filename as argument. You just need to change the function declaration to this:
def xmlparse(filename):
Then, you might also want to move your for
loop from the middle of your script to the bottom of your script. You could then call xmlparse
with each filename returned by find_files
like this:
for filename in find_files('c:/Python27','*file.xml'):
print ('Found file.xml:', filename)
xmlparse(filename)
Following your recent edit, you might also want to fix your xmlparse
function to loop over each year instead of just the last year:
for item in itemlist:
year = item.getElementsByTagName('Year')
for s in year:
print item.attributes['name'].value, s.attributes['value'].value
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.