[Tutor] Can This Script Be Modified to Read Many Files?..

Bob Gailer bgailer at gmail.com
Mon Jan 25 18:41:10 EST 2016


On Jan 25, 2016 6:26 PM, "Sam Starfas via Tutor" <tutor at python.org> wrote:
>
> Hi,I am very new to Python, but having fun learning.
> I need to have a script read all of the XML files contents that are in a
directory, pull out the contents of an element, in my case <uicontrol>, and
list them in an output file. I have this script that does exactly what I
need. But in my beginning Python class we didn't go over reading all files,
only one file at a time.
> Can the below script be modified to scan/read all of the XML files in a
directory instead of just the file typed into the script? If so, how do I
do this?
> Thanks for all the help.Sam
>
> import xml.etree.ElementTree as ETtree = ET.parse('TEST.xml')   <-- Want
to read all the files in directory, not type in the filename.root =
tree.getroot()
>
> for uicontrol in root.iter('uicontrol'):    print(uicontrol.text)
As you probably noticed your code got mangled this is probably due to the
email program you're using what you should do is have it send plain text so
the formatting will be preserved.
I hope it's obvious that you will need a loop to process multiple files so
I'm going to assume that what you want is how to get a list of files
meeting some criteria in a directory. I'm dictating into my cell phone
right now so I can't look some things up but my presumption is you will
need to use the glob function in the glob module to get the list of
filenames, then iterate over that list. Hope that helps.


More information about the Tutor mailing list