我在脚本所在的目录中有一个名为 junit.xml 的 XML 文件,我可以通过以下方式解析它:
xml_file = os.path.abspath(__file__)
xml_file = os.path.dirname(xml_file)
xml_file = os.path.join(xml_file, "junit.xml")
root = ET.parse(xml_file).getroot(); # Where ET is the element tree
一切正常
但是,我有一个更复杂的例子,我需要解析一堆连续位于不同目录中的同名“junit.xml”文件。
目录如下:
\myhome\ireland\modules\builds\date1
\myhome\ireland\modules\builds\date2
\myhome\england\modules\builds\date1
\myhome\england\modules\builds\date2
\myhome\scotland\modules\builds\date1
\myhome\scotland\modules\builds\date2
\myhome\wales\modules\builds\date1
\myhome\wales\modules\builds\date2
\myhome\germany\modules\builds\date1
\myhome\germany\modules\builds\date2
现在,每个目录都有 XML 文件的集合。我只想获取所有名为 junit.xml 的文件:
\myhome\ireland\modules\builds\date2
\myhome\england\modules\builds\date2
\myhome\scotland\modules\builds\date2
我如何以 pythonic 方式执行此操作,以便在需要时更改国家/地区名称和日期?
最佳答案
路径使用字符串模板,例如:
path = r"\myhome\{}\modules\builds\date{}"
稍后您可以使用 str.format()
构建真实路径函数(例如 path.format("ireland", 1)
)。
然后,您可以遍历国家名称和日期,并为每一个解析 XML 文件:
for country in ["ireland", "england", "scotland"]:
for num in [1, 2]:
parse_xml(path.format(country, num))
parse_xml
是您定义的函数,它获取 XML 文件的路径并对其进行解析。
关于python - 从多个位置读取相同的文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8977959/