python - 从多个位置读取相同的文件名

标签 python string

我在脚本所在的目录中有一个名为 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/

相关文章:

python - Docker 找不到我在 MacOS Big Sur 上添加到文件共享的路径

python - 带有 MultiIndex : check if string is contained in index level 的 Pandas 数据框

python - 从 stdout 获取原始流数据到 python 程序

string - 可以一次使用多个 BASH 变量操作吗?

python - 字符串的一部分与字典键字符串匹配

python - python内置@property如何接收重载的setter函数?

Python加入两个具有相似内容的字典

string - 将每个句子的首字母大写

c - Google Protobuf-c 重复字符串

objective-c - 格式字符串,带前导零的整数